JavaScript

JavaScript is a computer language with a name licensed to Oracle&reg;. JavaScript (JS) is a scripting language and as such it has fewer capabilities than full-fledged computer languages like C, Java, or C++. Its name seems to imply that it is a scripting variant of the computer language Java, which it is not, although the JS syntax (loops, Boolean expressions, etc.) is reminiscent of  Java.

JavaScript programs are usually embedded in a host environment, such as Web browsers or Windows Script Host. The embedded version of the language is known as client-side JS. Client-side JS has no built-in support for reading or writing files, such actions must be performed by the host. Being present in all Web browsers of today (2012), JavaScript is probably used more than any other programming language in the world.

Brendan Eich designed the language for one of the early Web browsers, Netscape Navigator, and gave it the name LiveScript. LiveScript was part of Netscape Navigator 2.0, released in September 1995. In an announcement of Netscape and Sun Microsystems dated December 4, 1995 the language was renamed to JavaScript; it is generally assumed that the name change was for marketing reasons. In June 1997 the European Computer Manufacturers Association (ECMA) published a standard for the language called ECMAScript-1  (for legal reasons it was not called JavaScript). In December 1999 ECMAScript-3 appeared, which is the most widely used version of the language. It is compatible with Netscape/Mozilla JavaScript v. 1.5 and Microsoft&reg; JScript 5.5. In June 2011 the standard ECMAScript-5.1 appeared. The specification for ECMAScript-4 was never published.

JavaScript is loosely typed, which means that the data types of variables are not declared explicitly. One cannot assign a priori a variable to a number, a string, or any other of the data types allowed by JS.

The language is often described as object oriented, but it is better called prototype oriented, a concept that was pioneered in the programming language Self. A prototype is a property of a constructor function that can be created and changed dynamically (during execution of the script). The inheritance of properties of instances proceeds through the prototype properties of the constructors in the inheritance chain.

JS shares with functional languages, such as the Lisp dialect Scheme, the fact that functions are first class entities. This means that a function can be returned as parameter from another function and can be assigned to a variable. Also, a function can enter another function as argument. Furthermore, a function may be nested within another function (its "host") and the nested function has access to the variables (lexical environment) of its host. Often such access takes place after the host has returned the nested function (which is assigned to a variable) and finished execution. When the nested function is later invoked it still has read/write access to the variables in its lexical environment. This so-called closure of the nested function over its lexical environment, which originated in Scheme, is typical for modern functional programming languages. JavaScript's closure and prototype inheritance are features that are not found in older imperative computer programming languages such as C or Fortran.

Small JavaScript example for use in a web browser
Writing a line to a web page written in HTML (hypertext markup language) is done by invoking the method write of the object document. Thus, the JS statement document.write("Hello, world") can be used to write the string  Hello, world   to the screen. However, first the web browser must be told that one or more lines of JS are appearing among the HTML lines. This is done by sandwiching the code between the HTML tags &lt;script> and &lt;/script>. That is, document.write("Hello, world"); appends the string  Hello, world   to the web page written before the tag &lt;script>.

JavaScript has a constructor Date. This constructor creates an object that contains the current date and time. Date offers many methods to format the current date. One of them is the method toLocaleDateString, which returns a string containing the date according to local conventions (local means the country where the computer, doing the browsing, is registered). In the Netherlands: var dateNow = new Date; document.write(dateNow.toLocaleDateString); writes something like maandag 24 oktober 2011. (Or whatever the actual weekday/month is). The new</tt> statement creates the new object dateNow</tt> that inherits the method toLocaleDateString</tt> from its constructor. The output of the method is a string containing the current weekday followed by day, month, and year. As is common in object-oriented programming languages, the method is invoked as suffix of the object separated by a dot: obj.mthod</tt> is the statement that lets mthod</tt> act on obj</tt>.

Summary of JavaScript's characteristics
The most noticeable properties of the programming language JavaScript are:
 * Syntax: JS's syntax is close to that of Java.
 * Imperative language: JS has the same command repertoire as imperative languages like C (assignments, functions, loops, logical statements).
 * Objects: JS supports objects. Objects can be accessed as associative arrays (string in square brackets) or by object notation (suffix separated by period).
 * Arrays: JS supports arrays that are created dynamically. An array element can be any legitimate JavaScript object.
 * Prototype-based inheritance: JS's inheritance rules differ from  object-oriented programming languages that employ class-based inheritance.
 * Functional programming: JS is a functional programming language;  functions are first-class, i.e., ordinary objects. There is support of nested functions and closures. In ECMAScript-3 variables have function scope and not block scope.
 * Regular expressions: JS supports regular expressions that are to a large extent compatible with those of Perl.

In the next sections the properties of core JavaScript, listed above, will be exemplified. These sections do not contain an exhaustive description of JS, they give only the flavor of the language; see Ref. for the complete language. Most lines in the examples below contain JavaScript comments&mdash;preceded by //. Values are printed to the screen by means of the method log</tt> of the object console</tt>. The values printed by console.log(.., ..)</tt> are usually given in a comment preceded by =>.

Declaration
Variables local to functions are declared by var</tt>. Omitting a declaration makes a variable global (accessible from any function). In the var</tt> statement initial values may be assigned.
 * Example:

Functions
JavaScript knows functions that, as in all computer languages, perform specific well-defined tasks. JS functions do not have to return a value. If no value is returned explicitly, a function returns the default value undefined</tt> (a built-in primitive JavaScript value). The syntax of the JS function statement is    function name(p1, p2, ...){ zero or more JS statements }

where p1, p2, ... </tt> are function parameters. Even if the function does not have parameters, a pair of matching parentheses is required. The function body (statements between curly brackets) can consist of any statements, including function statements. The function name</tt> is invoked by name(arg1, arg2, ..)</tt>. If a value is to be returned, or if an early return to the calling subprogram is needed, the return</tt> statement can be used.
 * Example:

The function statement above is similar to the procedure definition present in all imperative languages. As a functional language, JS has also the possibility to assign a function expression to a variable (the right-hand side is the function expression, the left-hand side contains the name of a variable that is bound to a function):


 * <tt> var fnc = function{ body }; </tt>

Often the function in a function expression (also known as a function literal) is unnamed (an anonymous function). A function literal may have a name, which then is mainly used in recursive invocations of the function (JS allows recursive function calls).

Loops
JavaScript knows a for loop, a while loop and a do/while loop. In three examples the following sum will be computed:

S_n := \sum_{i=0}^n i = n(n+1)/2 $$ for n = 10, that is, S10 = 55.

1. The for loop has the schematic syntax:
 * <tt> for (initialization; test; increment) {loop body}</tt>.


 * Example:

The statement <tt>sum += i</tt> is shorthand for <tt>sum = sum+i</tt>; <tt>i++</tt> assigns <tt>i</tt> adds 1 to <tt>i</tt> and stores the updated <tt>i</tt>.

2. The while loop has the schematic syntax:
 * <tt> initialization; while (expression) {loop body} </tt>

where <tt>expression</tt> has the value true or false.


 * Example:

3. The do/while loop contains a "post check", the body of the loop is executed at least once. Schematic syntax:
 * <tt> do {loop body} while (expression)  </tt>


 * Example:

Logical expression
The main form of the logical expression has the symbolic syntax:
 * <tt> if (expression) {statements;} else {statements;} </tt>

where <tt>expression</tt> must have value true or false. The <tt>statements</tt> can be any JS statements, including other logical expressions.
 * Example:

Objects
The easiest way to create an object in JavaScript is as a literal: <tt>{name1: value1, name2: value2, ...}</tt>, where <tt>value1</tt>, <tt>value2</tt>, ... can be any legitimate JavaScript entity, including an object or array.

Example
An object with three properties that have the respective values: a string, a mathematical constant, and another object is created. This prints: s String c 3.141592653589793 o ({s1:"Again", c1:3.33}) In the loop <tt>k</tt> receives the consecutive property names of the object <tt>obj</tt> and the array-type access <tt>obj[k]</tt> gives the corresponding value. Alternatively one could use object (dot) notation to print the values of the three properties of <tt>obj</tt>: yielding: String 3.141592653589793 ({s1:"Again", c1:3.33})

Arrays
An array literal is created by <tt>[ value0, value1, ...]</tt>. An array element can have any value:, string, constant, object, function, or array. The elements of an array are indexed by integer numbers starting with zero.

Example
This yields: 0  (function f {}) ({a:"AA", b:"B"}) -0.00001

Prototype inheritance
JavaScript's prototype inheritance mechanism will be explained by means of a small example.

Every JavaScript function has a property <tt>prototype</tt>, which is an object with properties that may be inherited by other objects. Certain functions are meant to serve as constructors of objects and it is convention to give those functions names beginning with a capital. In the simple example below the function named <tt>C</tt> serves as the constructor of the object <tt>obj</tt>:

Explanation
The operator <tt>new</tt> does two things: it creates the object named <tt>obj</tt> and it executes <tt>C</tt> with argument <tt>"prop"</tt>. During execution of any constructor function the keyword <tt>this</tt> obtains the value of the left-hand side of <tt>new</tt>. In this example <tt>this</tt> obtains the value <tt>obj</tt> and during execution of <tt>C</tt> the object <tt>obj</tt> is extended with a property named <tt>prop</tt> having as value the string <tt>"Property"</tt>.

After the creation of <tt>obj</tt>, the object <tt>C.prototype</tt> is extended with the method (function) <tt>m</tt>. For the sake of the example a simple method is chosen: all <tt>m</tt> does is returning its  parameter <tt>x</tt> prefixed with the string <tt>"Returns "</tt>.

The crucial point of this example is that <tt>m</tt> has become a method of <tt>obj</tt>, invoked as <tt>obj.m("XYZ")</tt>. The object <tt>obj</tt> inherits the method <tt>m</tt> from <tt>C.prototype</tt>. This inheritance is dynamic: <tt>C.prototype.m</tt> was created after <tt>obj</tt> came into existence, yet <tt>obj</tt> can invoke the method <tt>m</tt>. Note that <tt>m</tt> is not an own property of <tt>obj</tt>, or in other words, it is inherited from <tt>C.prototype</tt>. Let us reiterate that the function <tt>C</tt> is the constructor of <tt>obj</tt> and that <tt>obj.m</tt> refers to <tt>C.prototype.m</tt>, not to  <tt>C.m</tt>.

JavaScript as functional language
Consider the next snippet of JavaScript code. The variable <tt>x</tt> is local to function <tt>host</tt>, but not to function <tt>nested</tt>. However, <tt>x</tt> is in the lexical environment of <tt>nested</tt>, meaning that <tt>nested</tt> has full read/write access to it. Further, functions are "first class objects" and may be returned as values. The statement <tt>var fnc=host</tt> invokes <tt>host</tt> and assigns its return parameter (the function <tt>nested</tt>) to <tt>fnc</tt>. After <tt>host</tt> has finished execution, its local variable <tt>x</tt> still exists and is accessible by <tt>fnc</tt> (which is bound to <tt>nested</tt>).

The function <tt>nested</tt> is simple, all it does is returning <tt>x</tt> and adding one to it (the operation ++ adds one and stores the updated <tt>x</tt>). The function <tt>fnc</tt> is called twice as argument of the print function <tt>console.log</tt>. Parameters of the enclosing function also belong to the lexical environment of the nested function. The following code snippet is completely equivalent with the last one, but now <tt>x</tt> appears as parameter of <tt>host</tt>: A nested function is "closed over" its lexical environment and therefore a function plus its lexical environment is referred to as a closure.

For didactic reasons the host and the nested function were given names ("host" and "nested", respectively). When they are used once only, there is no need for naming them and the following code fragment, in which the names <tt>host</tt> and <tt>nested</tt> are dropped, is again equivalent to the two snippets above:

Application
Closure is at the basis of the following example of JavaScript code running in a web browser. Web browsers offer many methods,among them <tt>setInterval</tt>, <tt>clearInterval</tt>, and <tt>setTimeout</tt>. The following piece of code counts down from 10 to 0 with intervals of one second (1000 msec) and prints the count down variable:

Explanation
Invocation of the browser (DOM) method: <tt>setInterval(f,msec)</tt> copies the function <tt>f</tt>  to an internal execution stack and executes it every <tt>msec</tt> millisecond. Because <tt>x</tt> is in the lexical environment of <tt>f</tt>, the closure <tt>f</tt> can update and print <tt>x</tt>. The method <tt>setInterval</tt> continues forever, but returns a process identification number (<tt>id</tt>) enabling the cancellation of the process. The closure returned by <tt>host</tt> and bound to the variable <tt>clear</tt> has access to <tt>id</tt> and invokes the DOM method <tt>clearInterval</tt> which  cancels the process identified by <tt>id</tt>. The closure <tt>clear</tt> is called by <tt>setTimeout</tt> after 11100 milliseconds, hence after <tt>f</tt> has been executed eleven times. Note that, in general, the invocation <tt>setTimeout(fnc, msec)</tt> has two parameters: the  function <tt>fnc</tt> that is called after <tt>msec</tt> milliseconds.

Regular expressions
Regular expressions (regexps) form a powerful tool to parse strings. A regexp literal is an object defined between slashes, as in: <tt>/pattern/</tt>, where <tt>pattern</tt> is an (often rather intricate) expression that governs the parsing. As an object, a regexp has methods, the most important being the method <tt>exec(string)</tt>. Here the argument <tt>string</tt> is the string to be parsed.

In the next example a Universal Resource Locator (URL) is parsed into a (i) protocol (i.e., http, htpps, ftp, etc.), (ii) a host, and (iii) a file name (including the path of the file). First, a rather arbitrary URL is assigned as string to the variable <tt>url</tt>. Second, a regexp literal (between slashes) is assigned to <tt>regexp</tt>. Then the method <tt>exec</tt> is invoked, which returns parts broken out of its argument <tt>url</tt> to elements of the array <tt>parsedURL</tt>. Finally, the array elements are assigned to variables with meaningful names that are printed. The main difficulty in the use of regular expressions is the composition of the parsing patterns. These patterns, which must match corresponding parts of the string being parsed, are often hard to read and debug.

In the present example the first caret (^) appearing in <tt>regexp</tt> means that matching is to begin at the first character of the string and \w means that the first character must be a word character, i.e., a character in any of the ranges [a-z], [A-Z], [0-9], or the underscore (_). The + following \w means that all (with at least one) word characters are matching until the escaped colon (\:) appears. The backslash indicates that the colon is to be taken literally and not to be seen as a special regexp character. In a URL the protocol field is ended with a colon, hence the string beginning with, and consisting of, word characters gives the protocol. The round brackets in (\w+) indicate that the matched string is to be transferred to the array on the left hand side. Hence <tt>parsedURL[1]</tt> contains the protocol part of the URL (in the example: <tt>http</tt>).

After the colon the matching is resumed: two slashes are expected in a URL to follow the colon. Since a slash is a character with special meaning, it also has to be escaped by a backslash: \/\/ matches two consecutive slashes. Within square brackets the caret means "not", that is [^\/] matches any character (including white space) except the slash. In other words, a host name can contain any character except a slash. The + indicates again one or more characters and round brackets ask for transfer of the string matched up to \/ (a slash) to the left hand side. Hence <tt>parsedURL[2]</tt> contains all characters (that can be anything except a slash)  between :// and /. Finally, * indicates zero or more matches and $ indicates end of string. Hence, any number of characters (including zero characters) matches the part of the URL that gives the file name and its path.