DG COMPUTER EDUCATION

Wednesday, 27 June 2012

Arrays


Arrays

An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.


That means that, for example, we can store 5 values of type int in an array without having to declare 5 different variables, each one with a different identifier. Instead of that, using an array we can store 5 different values of the same type, int for example, with a unique identifier.


For example, an array to contain 5 integer values of type int called billy could be represented like this:


 
where each blank panel represents an element of the array, that in this case are integer values of type int. These elements are numbered from 0 to 4 since in arrays the first index is always 0, independently of its length.


Like a regular variable, an array must be declared before it is used. A typical declaration for an array in C++ is:


type name [elements];
where type is a valid type (like int, float...), name is a valid identifier and the elements field (which is always enclosed in square brackets []), specifies how many of these elements the array has to contain.


Therefore, in order to declare an array called billy as the one shown in the above diagram it is as simple as:


 
int billy [5];




NOTE: The elements field within brackets [] which represents the number of elements the array is going to hold, must be a constant value, since arrays are blocks of non-dynamic memory whose size must be determined before execution. In order to create arrays with a variable length dynamic memory is needed, which is explained later in these tutorials.



Initializing arrays.

When declaring a regular array of local scope (within a function, for example), if we do not specify otherwise, its elements will not be initialized to any value by default, so their content will be undetermined until we store some value in them. The elements of global and static arrays, on the other hand, are automatically initialized with their default values, which for all fundamental types this means they are filled with zeros.


In both cases, local and global, when we declare an array, we have the possibility to assign initial values to each one of its elements by enclosing the values in braces { }. For example:


 
int billy [5] = { 16, 2, 77, 40, 12071 }; 




This declaration would have created an array like this:


 
The amount of values between braces { } must not be larger than the number of elements that we declare for the array between square brackets [ ]. For example, in the example of array billy we have declared that it has 5 elements and in the list of initial values within braces { } we have specified 5 values, one for each element.


When an initialization of values is provided for an array, C++ allows the possibility of leaving the square brackets empty [ ]. In this case, the compiler will assume a size for the array that matches the number of values included between braces { }:


 
int billy [] = { 16, 2, 77, 40, 12071 };




After this declaration, array billy would be 5 ints long, since we have provided 5 initialization values.



Accessing the values of an array.



In any point of a program in which an array is visible, we can access the value of any of its elements individually as if it was a normal variable, thus being able to both read and modify its value. The format is as simple as:


name[index]
Following the previous examples in which billy had 5 elements and each of those elements was of type int, the name which we can use to refer to each element is the following:


 
For example, to store the value 75 in the third element of billy, we could write the following statement:


 
billy[2] = 75;




and, for example, to pass the value of the third element of billy to a variable called a, we could write:


 
a = billy[2];




Therefore, the expression billy[2] is for all purposes like a variable of type int.


Notice that the third element of billy is specified billy[2], since the first one is billy[0], the second one isbilly[1], and therefore, the third one is billy[2]. By this same reason, its last element is billy[4]. Therefore, if we write billy[5], we would be accessing the sixth element of billy and therefore exceeding the size of the array.


In C++ it is syntactically correct to exceed the valid range of indices for an array. This can create problems, since accessing out-of-range elements do not cause compilation errors but can cause runtime errors. The reason why this is allowed will be seen further ahead when we begin to use pointers.


At this point it is important to be able to clearly distinguish between the two uses that brackets [ ] have related to arrays. They perform two different tasks: one is to specify the size of arrays when they are declared; and the second one is to specify indices for concrete array elements. Do not confuse these two possible uses of brackets [ ] with arrays.


1
2
int billy[5];         // declaration of a new array
billy[2] = 75;        // access to an element of the array. 




If you read carefully, you will see that a type specifier always precedes a variable or array declaration, while it never precedes an access.


Some other valid operations with arrays:


1
2
3
4
billy[0] = a;
billy[a] = 75;
b = billy [a+2];
billy[billy[a]] = billy[2] + 5;




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// arrays example
#include <iostream>
using namespace std;

int billy [] = {16, 2, 77, 40, 12071};
int n, result=0;

int main ()
{
  for ( n=0 ; n<5 ; n++ )
  {
    result += billy[n];
  }
  cout << result;
  return 0;
}
12206





Multidimensional arrays



Multidimensional arrays can be described as "arrays of arrays". For example, a bidimensional array can be imagined as a bidimensional table made of elements, all of them of a same uniform data type.


 
jimmy represents a bidimensional array of 3 per 5 elements of type int. The way to declare this array in C++ would be:


 
int jimmy [3][5];




and, for example, the way to reference the second element vertically and fourth horizontally in an expression would be: 


 
jimmy[1][3]




 
(remember that array indices always begin by zero).


Multidimensional arrays are not limited to two indices (i.e., two dimensions). They can contain as many indices as needed. But be careful! The amount of memory needed for an array rapidly increases with each dimension. For example:


 
char century [100][365][24][60][60];




declares an array with a char element for each second in a century, that is more than 3 billion chars. So this declaration would consume more than 3 gigabytes of memory!


Multidimensional arrays are just an abstraction for programmers, since we can obtain the same results with a simple array just by putting a factor between its indices:


1
2
int jimmy [3][5];   // is equivalent to
int jimmy [15];     // (3 * 5 = 15) 




With the only difference that with multidimensional arrays the compiler remembers the depth of each imaginary dimension for us. Take as example these two pieces of code, with both exactly the same result. One uses a bidimensional array and the other one uses a simple array: 


multidimensional arraypseudo-multidimensional array
#define WIDTH 5
#define HEIGHT 3

int jimmy [HEIGHT][WIDTH];
int n,m;

int main ()
{
  for (n=0;n<HEIGHT;n++)
    for (m=0;m<WIDTH;m++)
    {
      jimmy[n][m]=(n+1)*(m+1);
    }
  return 0;
}
#define WIDTH 5
#define HEIGHT 3

int jimmy [HEIGHT * WIDTH];
int n,m;

int main ()
{
  for (n=0;n<HEIGHT;n++)
    for (m=0;m<WIDTH;m++)
    {
      jimmy[n*WIDTH+m]=(n+1)*(m+1);
    }
  return 0;
}


None of the two source codes above produce any output on the screen, but both assign values to the memory block called jimmy in the following way: 


 
We have used "defined constants" (#define) to simplify possible future modifications of the program. For example, in case that we decided to enlarge the array to a height of 4 instead of 3 it could be done simply by changing the line:


 
#define HEIGHT 3 


to:
 
#define HEIGHT 4 




with no need to make any other modifications to the program. 


Arrays as parameters

At some moment we may need to pass an array to a function as a parameter. In C++ it is not possible to pass a complete block of memory by value as a parameter to a function, but we are allowed to pass its address. In practice this has almost the same effect and it is a much faster and more efficient operation.


In order to accept arrays as parameters the only thing that we have to do when declaring the function is to specify in its parameters the element type of the array, an identifier and a pair of void brackets []. For example, the following function: 


 
void procedure (int arg[])




accepts a parameter of type "array of int" called arg. In order to pass to this function an array declared as:


 
int myarray [40];




it would be enough to write a call like this:


 
procedure (myarray);




Here you have a complete example: 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// arrays as parameters
#include <iostream>
using namespace std;

void printarray (int arg[], int length) {
  for (int n=0; n<length; n++)
    cout << arg[n] << " ";
  cout << "\n";
}

int main ()
{
  int firstarray[] = {5, 10, 15};
  int secondarray[] = {2, 4, 6, 8, 10};
  printarray (firstarray,3);
  printarray (secondarray,5);
  return 0;
}
5 10 15
2 4 6 8 10




As you can see, the first parameter (int arg[]) accepts any array whose elements are of type int, whatever its length. For that reason we have included a second parameter that tells the function the length of each array that we pass to it as its first parameter. This allows the for loop that prints out the array to know the range to iterate in the passed array without going out of range.


In a function declaration it is also possible to include multidimensional arrays. The format for a tridimensional array parameter is:


 
base_type[][depth][depth]




for example, a function with a multidimensional array as argument could be: 


 
void procedure (int myarray[][3][4])




Notice that the first brackets [] are left empty while the following ones specify sizes for their respective dimensions. This is necessary in order for the compiler to be able to determine the depth of each additional dimension.


Arrays, both simple or multidimensional, passed as function parameters are a quite common source of errors for novice programmers. I recommend the reading of the chapter about Pointers for a better understanding on how arrays operate.

BHARATHIDASAN UNIVERSITY RESULTS

Monday, 25 June 2012

Java Applet


Java Applet Tutorial

Designers and artists: this tutorial emphasizes visual and interactive aspects of applets. It was made especially for people wishing to create small, graphical, expressive forms with Java. However, if you have no programming experience at all, you'll probably need additional learning resources. Please see the note below for first-time programmers.
Before getting started, you'll need a compiler for Java, so that you can translate source code into something executable. You could, for example, download Sun's Java Software Development Kit (abbreviated as JDK or SDK), which includes a compiler, utilities, example applets, and a boat-load of documentation. (Mac users can try here, here and here.) Be sure to get the Java SDK and not the JRE (Java Runtime Environment) -- the former allows you to compile java programs, the latter only allows you to run them.
After getting a compiler, you can try out the examples. The first one, "Drawing Lines", walks you through the process of creating an applet. Please note that lessons 9-12 are unfinished, as I have yet to get around to completing them.
1 Drawing Lines
2 Drawing Other Stuff
3 Color - introduces arrays
4 Mouse Input - introduces showStatus( ) and Vector
5 Keyboard Input
6 Threads and Animation - introduces System.out.println( )
7 Backbuffers - introduces Math.random( ) and Graphics.drawImage( )
8 Painting
9 Clocks
10 Playing with Text - introduces 2D arrays and hyperlinks
11 3D Graphics - introduces classes
12 Odds and Ends
              

All of these examples were designed to be small and, hopefully, easy to absorb. If you couldn't find information here that you need, you might try Sun's website, which has copious documentation on Java, along with online tutorials and examples. You might also try the Java FAQ, a copy of which can be found by searching for "java faq" in any good search engine (or just try here -- the same site also hosts a tutorial).
If you're looking for books on Java, O'Reilly publishes some good ones, although they are most useful to people with at least a bit of prior programming experience. Java in a Nutshell by David Flanagan (in its 3rd edition, at the time of writing) covers the basic features of Java, including the syntax of the language, data structures, object-oriented features, and threads. Determined novices with no programming experience may find it useful.Java Foundation Classes in a Nutshell by David Flanagan describes how to create GUIs with widgets and how to draw basic graphics, among other things. Java 2D Graphics by Jonathan Knudsen, also published by O'Reilly, discusses in detail the graphics features of the Java 2 platform.
First-time programmers will probably find that the explanations given in this tutorial are too brief and leave out too many details. Basic information on the Java language can be found here (try to focus on understanding the syntax of variables, expressions, loops, and flow control structures at first -- we hardly make use of any object-oriented concepts in this tutorial). There are some books on Java for first-time programmers: this siterecommends Java: An Introduction to Computer Science and Programming by Walter Savitch et al., Problem Solving With Java by Elliot B. Koffman and Ursula Wolz, and Introduction to Programming Using Java: An Object-Oriented Approach by David M. Arnow and Gerald Weiss. You might also try getting a feel for some basic programming concepts by learning a simpler language first, such as DBN.

Sunday, 24 June 2012

JavaScript


JavaScript (sometimes abbreviated JS) is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is amulti-paradigm language, supporting object-oriented,[5] imperative, and functional[1][6] programming styles.
JavaScript was formalized in the ECMAScript language standard and is primarily used in the form of client-side JavaScript, implemented as part of aWeb browser in order to give enhanced user interfaces and dynamic websites. This enables programmatic access to computational objects within a host environment.
JavaScript's use in applications outside Web pages — for example in PDF documents, site-specific browsers, and desktop widgets — is also significant. Newer and faster JavaScript VMs and frameworks built upon them (notably Node.js) have also increased the popularity of JavaScript for server-side web applications.
JavaScript uses syntax influenced by that of C. JavaScript copies many names and naming conventions from Java, but the two languages are otherwise unrelated and have very different semantics. The key design principles within JavaScript are taken from the Self and Scheme programming languages.[7]

Contents

  [hide] 

[edit]History

JavaScript was originally developed in Netscape, by Brendan Eich. Battling with Microsoft over the Internet, Netscape considered their client-server solution as a distributed OS, running a portable version of Sun Microsystem's Java. Because Java was a competitor of C++ and aimed at professional programmers, Netscape also wanted a lightweight interpreted language that would complement Java by appealing to nonprofessional programmers, like Microsoft's VB.[9] (see JavaScript and Java)Birth at Netscape

Developed under the name Mocha, LiveScript was the official name for the language when it first shipped in beta releases of Netscape Navigator 2.0 in September 1995, but it was renamed JavaScript[10] when it was deployed in the Netscape browser version 2.0B3.[11]
The change of name from LiveScript to JavaScript roughly coincided with Netscape adding support for Java technology in its Netscape Navigator web browser. The final choice of name caused confusion, giving the impression that the language was a spin-off of the Java programming language, and the choice has been characterized by many as a marketing ploy by Netscape to give JavaScript the cachet of what was then the hot new web programming language.[12][13] It has also been claimed that the language's name is the result of a co-marketing deal between Netscape and Sun, in exchange for Netscape bundling Sun's Java runtime with its then-dominant browser.

[edit]Server-side JavaScript

Netscape introduced an implementation of the language for server-side scripting with Netscape Enterprise Server, first released in December, 1994 (soon after releasing JavaScript for browsers).[14][15] Since the mid-2000s, there has been a proliferation of server-side JavaScript implementations. node.js is one recent notable example of server-side JavaScript being used in real-world applications.[16][17]

[edit]Adoption by Microsoft

JavaScript very quickly gained widespread success as a client-side scripting language for web pages. Microsoft introduced JavaScript support in its own web browser, Internet Explorer, in version 3.0, released in August 1996.[18][not in citation given] Microsoft's webserver, Internet Information Server, introduced support for server-side scripting in JavaScript with release 3.0 (1996). Microsoft started to promote webpage scripting using the umbrella term Dynamic HTML.
Microsoft's JavaScript implementation was later renamed JScript to avoid trademark issues. JScript added new date methods to fix the Y2K-problematic methods in JavaScript, which were based on Java's java.util.Date class.

[edit]Standardization

In November 1996, Netscape announced that it had submitted JavaScript to Ecma International for consideration as an industry standard, and subsequent work resulted in the standardized version named ECMAScript.[19]

[edit]Later developments

JavaScript has become one of the most popular programming languages on the web. Initially, however, many professional programmers denigrated the language because its target audience was web authors and other such "amateurs", among other reasons.[20] The advent of Ajax returned JavaScript to the spotlight and brought more professional programming attention. The result was a proliferation of comprehensive frameworks and libraries, improved JavaScript programming practices, and increased usage of JavaScript outside of web browsers, as seen by the proliferation ofserver-side JavaScript platforms.
In January 2009, the CommonJS project was founded with the goal of specifying a common standard library mainly for JavaScript development outside the browser.[21]

[edit]Trademark

Today, "JavaScript" is a trademark of Oracle Corporation.[22] It is used under license for technology invented and implemented by Netscape Communications and current entities such as theMozilla Foundation.[23]

[edit]Features

The following features are common to all conforming ECMAScript implementations, unless explicitly specified otherwise.

[edit]Imperative and structured

JavaScript supports much of the structured programming syntax from C (e.g., if statements, while loops, switch statements, etc.). One partial exception is scoping: C-style block-level scoping is not supported (instead, JavaScript has function-level scoping). JavaScript 1.7, however, supports block-level scoping with the let keyword. Like C, JavaScript makes a distinction between expressions and statements. One syntactic difference from C is automatic semicolon insertion, in which the semicolons that terminate statements can be omitted.[24]

[edit]Dynamic

dynamic typing
As in most scripting languages, types are associated with values, not with variables. For example, a variable x could be bound to a number, then later rebound to a string. JavaScript supports various ways to test the type of an object, including duck typing.[25]
object based
JavaScript is almost entirely object-based. JavaScript objects are associative arrays, augmented with prototypes (see below). Object property names are string keys: obj.x = 10 andobj['x'] = 10 are equivalent, the dot notation being syntactic sugar. Properties and their values can be added, changed, or deleted at run-time. Most properties of an object (and those on its prototype inheritance chain) can be enumerated using a for...in loop. JavaScript has a small number of built-in objects such as Function and Date.
run-time evaluation
JavaScript includes an eval function that can execute statements provided as strings at run-time.

[edit]Functional

first-class functions
Functions are first-class; they are objects themselves. As such, they have properties and methods, such as length and call();[26] and they can be assigned to variables, passed as arguments, returned by other functions, and manipulated like any other object.[27] Any reference to a function allows it to be invoked using the () operator.[28]
nested functions and closures
"Inner" or "nested" functions are functions defined within another function. They are created each time the outer function is invoked. In addition to that, each created function forms a lexical closure: the lexical scope of the outer function, including any constants, local variables and argument values, become part of the internal state of each inner function object, even after execution of the outer function concludes.[29]

[edit]Prototype-based

prototypes
JavaScript uses prototypes instead of classes for inheritance. It is possible to simulate many class-based features with prototypes in JavaScript.
functions as object constructors
Functions double as object constructors along with their typical role. Prefixing a function call with new creates a new object and calls that function with its local this keyword bound to that object for that invocation. The constructor's prototype property determines the object used for the new object's internal prototype. JavaScript's built-in constructors, such as Array, also have prototypes that can be modified.
functions as methods
Unlike many object-oriented languages, there is no distinction between a function definition and a method definition. Rather, the distinction occurs during function calling; a function can be called as a method. When a function is called as a method of an object, the function's local this keyword is bound to that object for that invocation.

[edit]Miscellaneous

run-time environment
JavaScript typically relies on a run-time environment (e.g. in a web browser) to provide objects and methods by which scripts can interact with "the outside world". In fact, it relies on the environment to provide the ability to include/import scripts (e.g. HTML <script> elements). (This is not a language feature per se, but it is common in most JavaScript implementations.)
variadic functions
An indefinite number of parameters can be passed to a function. The function can access them through formal parameters and also through the local arguments object.
array and object literals
Like many scripting languages, arrays and objects (associative arrays in other languages) can each be created with a succinct shortcut syntax. In fact, these literals form the basis of theJSON data format.
regular expressions
JavaScript also supports regular expressions in a manner similar to Perl, which provide a concise and powerful syntax for text manipulation that is more sophisticated than the built-in string functions.

[edit]Vendor-specific extensions

JavaScript is officially managed by Mozilla Foundation, and new language features are added periodically. However, only some non-Mozilla JavaScript engines support these new features:
  • property getter and setter functions (also supported by WebKit, Opera,[30] ActionScript, and Rhino)[31]
  • conditional catch clauses
  • iterator protocol adopted from Python
  • shallow generators-coroutines also adopted from Python
  • array comprehensions and generator expressions also adopted from Python
  • proper block scope via the let keyword
  • array and object destructuring (limited form of pattern matching)
  • concise function expressions (function(args) expr)
  • ECMAScript for XML (E4X), an extension that adds native XML support to ECMAScript

[edit]Syntax and semantics

As of 2011, the latest version of the language is JavaScript 1.8.5. It is a superset of ECMAScript (ECMA-262) Edition 3. Extensions to the language, including partial ECMAScript for XML (E4X) (ECMA-357) support and experimental features considered for inclusion into future ECMAScript editions, are documented here.[32]

[edit]Simple examples

There is no built-in I/O functionality in JavaScript; the runtime environment provides that. In a web browser, here is the simplest "hello world" example:
alert("Hello world!");
A simple recursive function:
function factorial(n) {
    if (n === 0) {
        return 1;
    }
    return n * factorial(n - 1);
}
Anonymous function (or lambda) syntax and closure example:
function displayClosure() {
    var count = 0;
    return function () {
        return ++count;
    };
}
var inc = displayClosure();
inc(); // returns 1
inc(); // returns 2
inc(); // returns 3
Variadic function demonstration (arguments is a special variable).
function sum() {
    var i, x = 0;
    for (i = 0; i < arguments.length; ++i) {
        x += arguments[i];
    }
    return x;
}
sum(1, 2, 3); // returns 6

[edit]More advanced example

This sample code showcases various JavaScript features.
/* Finds the lowest common multiple of two numbers */
function LCMCalculator(x, y) { // constructor function
    var checkInt = function (x) { // inner function
        if (x % 1 !== 0) {
            throw new TypeError(x + " is not an integer"); // throw an exception
        }
        return x;
    };
    this.a = checkInt(x);
    // ^ semicolons are optional
    this.b = checkInt(y);
}
// The prototype of object instances created by a constructor is
// that constructor's "prototype" property.
LCMCalculator.prototype = { // object literal
    constructor: LCMCalculator, // when reassigning a prototype, set the constructor property appropriately
    gcd: function () { // method that calculates the greatest common divisor
        // Euclidean algorithm:
        var a = Math.abs(this.a), b = Math.abs(this.b), t;
        if (a < b) {
            // swap variables
            t = b;
            b = a;
            a = t;
        }
        while (b !== 0) {
            t = b;
            b = a % b;
            a = t;
        }
        // Only need to calculate GCD once, so "redefine" this method.
        // (Actually not redefinition - it's defined on the instance itself,
        // so that this.gcd refers to this "redefinition" instead of LCMCalculator.prototype.gcd.)
        // Also, 'gcd' === "gcd", this['gcd'] === this.gcd
        this['gcd'] = function () {
            return a;
        };
        return a;
    },
    // Object property names can be specified by strings delimited by double (") or single (') quotes.
    "lcm" : function () {
        // Variable names don't collide with object properties, e.g. |lcm| is not |this.lcm|.
        // not using |this.a * this.b| to avoid FP precision issues
        var lcm = this.a / this.gcd() * this.b;
        // Only need to calculate lcm once, so "redefine" this method.
        this.lcm = function () {
            return lcm;
        };
        return lcm;
    },
    toString: function () {
        return "LCMCalculator: a = " + this.a + ", b = " + this.b;
    }
};
 
//define generic output function; this implementation only works for web browsers
function output(x) {
    document.body.appendChild(document.createTextNode(x));
    document.body.appendChild(document.createElement('br'));
}
 
// Note: Array's map() and forEach() are defined in JavaScript 1.6.
// They are used here to demonstrate JavaScript's inherent functional nature.
[[25, 55], [21, 56], [22, 58], [28, 56]].map(function (pair) { // array literal + mapping function
    return new LCMCalculator(pair[0], pair[1]);
}).sort(function (a, b) { // sort with this comparative function
    return a.lcm() - b.lcm();
}).forEach(function (obj) {
    output(obj + ", gcd = " + obj.gcd() + ", lcm = " + obj.lcm());
});
The following output should be displayed in the browser window.
LCMCalculator: a = 28, b = 56, gcd = 28, lcm = 56<br>
LCMCalculator: a = 21, b = 56, gcd = 7, lcm = 168<br>
LCMCalculator: a = 25, b = 55, gcd = 5, lcm = 275<br>
LCMCalculator: a = 22, b = 58, gcd = 2, lcm = 638<br>

[edit]Use in web pages

The most common use of JavaScript is to write functions that are embedded in or included from HTML pages and that interact with the Document Object Model (DOM) of the page. Some simple examples of this usage are:
  • Loading new page content or submitting data to the server via AJAX without reloading the page (for example, a social network might allow the user to post status updates without leaving the page)
  • Animation of page elements, fading them in and out, resizing them, moving them, etc.
  • Interactive content, for example games, and playing audio and video
  • Validating input values of a web form to make sure that they are acceptable before being submitted to the server.
  • Transmitting information about the user's reading habits and browsing activities to various websites. Web pages frequently do this for web analytics, ad tracking, personalization or other purposes.[33]
Because JavaScript code can run locally in a user's browser (rather than on a remote server), the browser can respond to user actions quickly, making an application more responsive. Furthermore, JavaScript code can detect user actions which HTML alone cannot, such as individual keystrokes. Applications such as Gmail take advantage of this: much of the user-interface logic is written in JavaScript, and JavaScript dispatches requests for information (such as the content of an e-mail message) to the server. The wider trend of Ajax programming similarly exploits this strength.
A JavaScript engine (also known as JavaScript interpreter or JavaScript implementation) is an interpreter that interprets JavaScript source code and executes the script accordingly. The first JavaScript engine was created by Brendan Eich at Netscape Communications Corporation, for the Netscape Navigator web browser. The engine, code-named SpiderMonkey, is implemented inC. It has since been updated (in JavaScript 1.5) to conform to ECMA-262 Edition 3. The Rhino engine, created primarily by Norris Boyd (formerly of Netscape; now at Google) is a JavaScript implementation in Java. Rhino, like SpiderMonkey, is ECMA-262 Edition 3 compliant.
A web browser is by far the most common host environment for JavaScript. Web browsers typically use the public API to create "host objects" responsible for reflecting the Document Object Model (DOM) into JavaScript. The web server is another common application of the engine. A JavaScript webserver would expose host objects representing an HTTP request and response objects, which a JavaScript program could then manipulate to dynamically generate web pages.
Because JavaScript is the only language that the most popular browsers share support for, it has become a target language for many frameworks in other languages, even though JavaScript was never intended to be such a language.[34] Despite the performance limitations inherent to its dynamic nature, the increasing speed of JavaScript engines has made the language a surprisingly feasible compilation target.

[edit]Example script

Below is a minimal example of a standards-conforming web page containing JavaScript (using HTML 4.01 syntax) and the DOM:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head><title>simple page</title></head>
  <body>
    <h1 id="header">This is JavaScript1</h1>
    <script type="text/javascript">
      document.body.appendChild(document.createTextNode('Hello World!'));
      var h1 = document.getElementById("header"); // holds a reference to the <h1> tag
      h1 = document.getElementsByTagName("h1")[0]; // accessing the same <h1> element
    </script>
    <noscript>Your browser either does not support JavaScript, or has JavaScript turned off.</noscript>
  </body>
</html>

[edit]Compatibility considerations

Because JavaScript runs in widely varying environments, an important part of testing and debugging is to test and verify that the JavaScript works across multiple browsers.
The DOM interfaces for manipulating web pages are not part of the ECMAScript standard, or of JavaScript itself. Officially, the DOM interfaces are defined by a separate standardization effort by the W3C; in practice, browser implementations differ from the standards and from each other, and not all browsers execute JavaScript.
To deal with these differences, JavaScript authors can attempt to write standards-compliant code which will also be executed correctly by most browsers; failing that, they can write code that checks for the presence of certain browser features and behaves differently if they are not available.[35] In some cases, two browsers may both implement a feature but with different behavior, and authors may find it practical to detect what browser is running and change their script's behavior to match.[36][37] Programmers may also use libraries or toolkits which take browser differences into account.
Furthermore, scripts may not work for some users. For example, a user may:
  • use an old or rare browser with incomplete or unusual DOM support,
  • use a PDA or mobile phone browser which cannot execute JavaScript,
  • have JavaScript execution disabled as a security precaution,
  • use a speech browser due to, for example, a visual disability.
To support these users, web authors can try to create pages which degrade gracefully on user agents (browsers) which do not support the page's JavaScript. In particular, the page should remain usable albeit without the extra features that the JavaScript would have added. An alternative approach that many find preferable is to first author content using basic technologies that work in all browsers, then enhance the content for users that have JavaScript enabled. This is known as progressive enhancement.

[edit]Accessibility

Assuming that the user has not disabled its execution, client-side web JavaScript should be written to enhance the experiences of visitors with visual or physical disabilities, and certainly should avoid denying information to these visitors.[38]
Screen readers, used by the blind and partially sighted, can be JavaScript-aware and so may access and read the page DOM after the script has altered it. The HTML should be as concise, navigable and semantically rich as possible whether the scripts have run or not. JavaScript should not be totally reliant on mouse-specific events so as to deny its benefits to users who either cannot use a mouse or who choose to favor the keyboard for whatever reason. Equally, although hyperlinks and webforms can be navigated and operated from the keyboard, accessible JavaScript should not require keyboard events either. There are device-independent events such as onfocus and onchange that are preferable in most cases.[38]
JavaScript should not be used in a way that is confusing or disorienting to any web user. For example, using script to alter or disable the normal functionality of the browser, such as by changing the way the back-button or the refresh event work, is usually best avoided. Equally, triggering events that the user may not be aware of reduces the user's sense of control as do unexpected scripted changes to the page content.[39]
Often the process of making a complex web page as accessible as possible becomes a nontrivial problem where issues become matters of debate and opinion, and where compromises are necessary in the end. However, user agents and assistive technologies are constantly evolving and new guidelines and relevant information are continually being published on the web.[38]

[edit]Security

JavaScript and the DOM provide the potential for malicious authors to deliver scripts to run on a client computer via the web. Browser authors contain this risk using two restrictions. First, scripts run in a sandbox in which they can only perform web-related actions, not general-purpose programming tasks like creating files. Second, scripts are constrained by the same origin policy: scripts from one web site do not have access to information such as usernames, passwords, or cookies sent to another site. Most JavaScript-related security bugs are breaches of either the same origin policy or the sandbox.

[edit]Cross-site vulnerabilities

A common JavaScript-related security problem is cross-site scripting, or XSS, a violation of the same-origin policy. XSS vulnerabilities occur when an attacker is able to cause a target web site, such as an online banking website, to include a malicious script in the webpage presented to a victim. The script in this example can then access the banking application with the privileges of the victim, potentially disclosing secret information or transferring money without the victim's authorization. A solution to XSS vulnerabilities is to use HTML escaping whenever displaying untrusted data.
Some browsers include partial protection against reflected XSS attacks, in which the attacker provides a URL including malicious script. However, even users of those browsers are vulnerable to other XSS attacks, such as those where the malicious code is stored in a database. Only correct design of Web applications on the server side can fully prevent XSS.
XSS vulnerabilities can also occur because of implementation mistakes by browser authors.[40]
Another cross-site vulnerability is cross-site request forgery or CSRF. In CSRF, code on an attacker's site tricks the victim's browser into taking actions the user didn't intend at a target site (like transferring money at a bank). It works because, if the target site relies only on cookies to authenticate requests, then requests initiated by code on the attacker's site will carry the same legitimate login credentials as requests initiated by the user. In general, the solution to CSRF is to require an authentication value in a hidden form field, and not only in the cookies, to authenticate any request that might have lasting effects. Checking the HTTP Referrer header can also help.
"JavaScript hijacking" is a type of CSRF attack in which a <script> tag on an attacker's site exploits a page on the victim's site that returns private information such as JSON or JavaScript. Possible solutions include:
  • requiring an authentication token in the POST and GET parameters for any response that returns private information
  • using POST and never GET for requests that return private information

[edit]Misplaced trust in the client

Developers of client-server applications must recognize that untrusted clients may be under the control of attackers. Thus any secret embedded in JavaScript could be extracted by a determined adversary, and the application author cannot assume that his JavaScript runs as intended, or at all. Some implications:
  • Web site authors cannot perfectly conceal how their JavaScript operates, because the code is sent to the client, and obfuscated code can be reverse-engineered.
  • JavaScript form validation only provides convenience for users, not security. If a site verifies that the user agreed to its terms of service, or filters invalid characters out of fields that should only contain numbers, it must do so on the server, not only the client.
  • Scripts can be selectively disabled, so JavaScript can't be relied on to prevent operations such as "save image".[41]
  • It is extremely bad practice to embed sensitive information such as passwords in JavaScript because it can be extracted by an attacker.

[edit]Browser and plugin coding errors

JavaScript provides an interface to a wide range of browser capabilities, some of which may have flaws such as buffer overflows. These flaws can allow attackers to write scripts which would run any code they wish on the user's system.
These flaws have affected major browsers including Firefox,[42] Internet Explorer,[43] and Safari.[44]
Plugins, such as video players, Adobe Flash, and the wide range of ActiveX controls enabled by default in Microsoft Internet Explorer, may also have flaws exploitable via JavaScript, and such flaws have been exploited in the past.[45][46]
In Windows Vista, Microsoft has attempted to contain the risks of bugs such as buffer overflows by running the Internet Explorer process with limited privileges.[47] Google Chrome similarly limits page renderers in its own "sandbox".

[edit]Sandbox implementation errors

Web browsers are capable of running JavaScript outside of the sandbox, with the privileges necessary to, for example, create or delete files. Of course, such privileges aren't meant to be granted to code from the web.
Incorrectly granting privileges to JavaScript from the web has played a role in vulnerabilities in both Internet Explorer[48] and Firefox.[49] In Windows XP Service Pack 2, Microsoft demoted JScript's privileges in Internet Explorer.[50]
Microsoft Windows allows JavaScript source files on a computer's hard drive to be launched as general-purpose, non-sandboxed programs. This makes JavaScript (like VBScript) a theoretically viable vector for a Trojan horse, although JavaScript Trojan horses are uncommon in practice.[51] (See Windows Script Host.)

[edit]Uses outside web pages

In addition to web browsers and servers, JavaScript interpreters are embedded in a number of tools. Each of these applications provides its own object model which provides access to the host environment, with the core JavaScript language remaining mostly the same in each application.

[edit]Embedded scripting language

  • Google's Chrome extensions, Opera's extensions, Apple's Safari 5 extensions, Apple's Dashboard Widgets, Microsoft's Gadgets, Yahoo! Widgets, Google Desktop Gadgets, and SerenceKlipfolio are implemented using JavaScript.
  • Adobe's Acrobat and Adobe Reader support JavaScript in PDF files.[52]
  • Tools in the Adobe Creative Suite, including Photoshop, Illustrator, Dreamweaver, and InDesign, allow scripting through JavaScript.
  • OpenOffice.org office application suite allows for JavaScript as one of its scripting languages.
  • The interactive music signal processing software Max/MSP released by Cycling '74, offers a JavaScript model of its environment for use by developers. It allows much more precise control than the default GUI-centric programming model.
  • ECMAScript was included in the VRML97 standard for scripting nodes of VRML scene description files.
  • Some high-end Philips universal remote panels, including TSU9600 and TSU9400, can be scripted using a JavaScript-based tool called ProntoScript.[53]
  • Sphere is an open source and cross platform computer program designed primarily to make role-playing games that use JavaScript as a scripting language.
  • The open-source Re-Animator framework allows developing 2D sprite-based games using JavaScript and XML.
  • Methabot is a web crawler that uses JavaScript as scripting language for custom filetype parsers and data extraction using E4X.
  • The Unity game engine supports a modified JavaScript for scripting (in addition to C# and Boo) via Mono.[54]
  • DX Studio (3D engine) uses the SpiderMonkey implementation of JavaScript for game and simulation logic.[55]
  • Maxwell Render (rendering software) provides an ECMA standard based scripting engine for tasks automation.[56]
  • Google Apps Script in Google Spreadsheets and Google Sites allows users to create custom formulas, automate repetitive tasks and also interact with other Google products such as Gmail.[57]
  • Many IRC clients, like ChatZilla or XChat, use JavaScript for their scripting abilities.[58][59]

[edit]Scripting engine

  • Microsoft's Active Scripting technology supports JScript as a scripting language.[60]
  • The Java programming language, in version SE 6 (JDK 1.6), introduced the javax.script package, including a JavaScript implementation based on Mozilla Rhino. Thus, Java applications can host scripts that access the application's variables and objects, much like web browsers host scripts that access the browser's Document Object Model (DOM) for a webpage.[61][62]
  • The Qt C++ toolkit includes a QtScript module to interpret JavaScript, analogous to Java's javax.script package.[63]
  • JSDB (JavaScript for Databases) is an open-source JavaScript shell for Windows, Mac OS X, Linux, and Unix, which extends the Mozilla JavaScript engine with file, database, email, and network objects.
  • jslibs is an open-source JavaScript shell for Windows and Linux which extends the Mozilla JavaScript engine. It has the ability to call functions in commonly used libraries like NSPR, SQLite, libTomCrypt, OpenGL, OpenAL, and librsvg.
  • Late Night Software's JavaScript OSA (aka JavaScript for OSA, or JSOSA) is a freeware alternative to AppleScript for Mac OS X. It is based on the Mozilla 1.5 JavaScript implementation, with the addition of a MacOS object for interaction with the operating system and third-party applications.[64]

[edit]Application platform

  • ActionScript, the programming language used in Adobe Flash, is another implementation of the ECMAScript standard.
  • The Mozilla platform, which underlies Firefox, Thunderbird, and some other web browsers, uses JavaScript to implement the graphical user interface (GUI) of its various products.
  • Adobe Integrated Runtime is a JavaScript runtime that allows developers to create desktop applications.
  • myNFC.org is a JavaScript based framework that allows developers to create applications for smart phones.
  • webOS uses the WebKit implementation of JavaScript in its SDK to allow developers to create stand-alone applications solely in JavaScript.
  • CA, Inc.'s AutoShell cross-application scripting environment is built on JavaScript/SpiderMonkey with preprocessor like extensions for command definitions and custom classes for various system related tasks like file i/o, operation system command invocation and redirection and COM scripting.
  • GNOME Shell, the shell for the GNOME 3 desktop environment.[65] The Seed,[66] Gjs (from Gnome), and Kjsembed[67] (from KDE) packages are aimed to utilize these[clarification needed]needs.[68][69]
  • Qt Quick's markup language (QML) is using JavaScript for the application logic, and the declarative syntax is JavaScript-like. QML has been available since Qt 4.7.