JavaScript syntax
The syntax of JavaScript is a set of rules that defines how a JavaScript program will be written and interpreted.
Data structures
Variables
Variables are generally dynamically typed.
Variables are defined by either just assigning them a value or by using the var
statement.
Variables declared outside of any function, and variables declared without the var
statement, are in "global" scope, visible in the entire web page; variables declared inside a function with the var
statement are local to that function.
To pass variables from one page to another, a developer can set a cookie or use a hidden frame or window in the background to store them. This approach relies on the browser DOM rather than anything in the JavaScript language itself.
A third way to pass variables between pages is to include them in the call for the next page. The list of arguments is preceded by a question mark, and each argument specification follows the format: name=value. The ampersand character is used as the list separator character. An example of this technique is sample.html?arg1=foo&arg2=bar
.
Numbers
Numbers in JavaScript are represented in binary as IEEE-754 Doubles, which provides an accuracy to about 14 or 15 significant digits JavaScript FAQ 4.7. Because they are binary numbers, they do not always exactly represent decimal numbers, particularly fractions.
This becomes an issue when formatting numbers for output (JavaScript has no methods to format number for output) For example:
alert(0.94 - 0.01) // displays 0.9299999999999999
As a result, rounding should be used whenever numbers are formatted for output. The toFixed() method is not part of the ECMAScript specification and is implemented differently in various environments, so it can't be relied upon.
Arrays
An Array is a map from integers to values. In JavaScript, all objects can map from integers to values, but
Arrays are a special type of object that has extra behavior and methods specializing in integer indices (e.g., join
, slice
, and push
).
Arrays have a length
property that is guaranteed to always be larger
than the largest integer index used in the array. It is automatically updated if one creates a property with an even larger index. Writing a smaller number to the length
property will remove larger indices. This length
property is the only special feature of Arrays that distinguishes it from other objects.
Elements of Arrays may be accessed using normal object property access notation:
myArray[1] myArray["1"]
These two are equivalent. It's not possible to use the "dot"-notation or strings with alternative representations of the number:
myArray.1 (syntax error) myArray["01"] (not the same as myArray[1])
Declaration of an array can use either an Array literal or the Array
constructor:
myArray = [0,1,,,4,5]; (array with length 6 and 4 elements) myArray = new Array(0,1,2,3,4,5); (array with length 6 and 6 elements) myArray = new Array(365); (an empty array with length 365)
Arrays are implemented so that only the elements defined use memory; they are "sparse arrays". Setting myArray[10] = 'someThing'
and myArray[57] = 'somethingOther'
only uses space for these two elements, just like any other object. The length
of the array will still be reported as 58.
Object literals allow one to define generic structured data:
var myStructure = { name: { first: "Mel", last: "Smith" }, age: 33, hobbies: [ "chess", "jogging" ] };
This syntax has its own standard, JSON.
Operators
Arithmetic operators
The '+' operator is overloaded; it is used for string concatenation and arithmetic addition and also to convert strings to numbers (not to mention that it has special meaning when used in a regular expression).
// Concatenate 2 strings var a = 'This'; var b = ' and that'; alert(a + b); // displays 'This and that' // Add two numbers var x = 2; var y = 6; alert(x + y); // displays 8 // Adding a number and a string results in concatenation alert( x + '2'); // displays 22 // Convert a string to a number var z = '4'; // z is a string (the digit 4) alert( z + x) // displays 42 alert( +z + x) // displays 6
Conditional operator
Also known as the ternary operator
condition ? statement : statement;
Control structures
If ... else
if (condition) { statements } else { statements }
switch (expression) { case label1 : statements; break; case label2 : statements; break; default : statements; }
Actually, break;
is optional. However leaving it out isn't recommended in most cases since otherwise code execution will continue to the body of the next case … :
.
for ([initial-expression]; [condition]; [increment-expression]) { statements }
For ... in loop
This loop goes through all enumerable properties of an object (or elements of an array).
for (slot in object) { statements involving object[slot] }
while (condition) { statements }
do { statements } while (condition);
Functions
A function is a block with a (possibly empty) argument list that is normally given a name. A function may give back a return value.
function function-name(arg1, arg2, arg3) { statements; return expression; }
Example: Euclid's original algorithm of finding the greatest common divisor. (This is a geometrical solution which subtracts the shorter segment from the longer):
function gcd(segmentA, segmentB) { while (segmentA != segmentB) { if (segmentA > segmentB) segmentA -= segmentB; else segmentB -= segmentA; } return segmentA; }
The number of arguments given when calling a function may not necessarily correspond to the number of arguments in the function definition; a named argument in the definition that does not have a matching argument in the call will have the value undefined
. Within the function the arguments may also be accessed through the arguments
list (which is an object); this provides access to all arguments using indices (e.g. arguments[0], arguments[1], ... arguments[n]
), including those beyond the number of named arguments.
Basic data types (strings, integers, ...) are passed by value whereas objects are passed by reference.
Functions as objects and anonymous functions
Functions are first-class objects in JavaScript. Every function is an instance of Function
, a type of base object. Functions can be created and assigned like any other objects, and passed as arguments to other functions. Thus JavaScript supports higher-order functions. For example:
Array.prototype.fold = function (value, functor) { var result = value; for (var i = 0; i < this.length; i++) { result = functor(result, this[i]); } return result; } var sum = [1,2,3,4,5,6,7,8,9,10].fold(0, function (a, b) { return a + b })
results in the value:
55
Since Function
can be instantiated, JavaScript allows the creation of anonymous functions, which can also be created using function, e.g.:
new Function( "return 1;" )
function() { return 1; }
The implicit object available within the function is the receiver object.
In the example below, the value of the alert property is an anonymous function:
function Point( x, y ) { this.x = x; this.y = y; } Point.prototype.alert = function() { window.alert( "(" + this.x + "," + this.y + ")" ); } var pt = new Point( 1, 0 ); pt.alert();
Methods can also be added within the constructor:
function Point( x, y ) { this.x = x; this.y = y; this.alert = function() { window.alert( "(" + this.x + "," + this.y + ")" ); } } var pt = new Point( 1, 0 ); pt.alert();
There is no need to use a constructor if only a single instance of an object is required and no private members are needed - properties and values can be added directly using an initialiser:
var pt = { x: 1, y: 0, alert: function() { window.alert( "(" + this.x + "," + this.y + ")" ); } } pt.alert();
Members declared as variables in the constructor are private; members assigned to this are public. Methods added or declared in the constructor have access to all private members; public methods added outside the constructor don't.
function myClass() { var msg = "Hello world!"; /* This is shorthand for: var myPrivateMember = function() */ function myPrivateMember() { alert(msg); } this.myPublicMember = function() { myPrivateMember(); } } myObj = new myClass; myObj.anotherPublicMember = function() { /* These won't work as anotherPublicMember is not declared in the constructor: myPrivateMember(); alert(msg); These won't work either: this.myPrivateMember(); alert(this.msg); */ this.myPublicMember(); }
Note: The functions '__defineSetter__' and '__defineGetter__' are implementation-specific and not part of the ECMAScript standard.
For detailed control of member access, getters and setters can be used (e.g. to create a read only property or a property that the value is generated):
function Point( x, y ) { this.x = x; this.y = y; } Point.prototype.__defineGetter__( "dimensions", function() { return [this.x, this.y]; } ); Point.prototype.__defineSetter__( "dimensions", function( dimensions ) { this.x = dimensions[0]; this.y = dimensions[1]; } ); var pt = new Point( 1, 0 ); window.alert( pt.dimensions.length ); pt.dimensions = [2,3];
Since JavaScript 1.3 every function has the methods apply and call
which allows the use of this function in the context of another object.
The statements F.apply ( myObj , [ a1 , a2 , ... , aN ] )
and F.call ( myObj , a1 , a2 , ... , aN )
performs F ( a1 , a2 , ... , aN ) as if this function would be a method of the object myObj.
function sum () { var s = 0; for ( var i = 0 ; i < arguments.length ; i++ ) s += arguments [i] ; return s } var dummy alert ( sum.apply ( dummy , [ 1 , 2 , 3 ] ) ) // == 1 + 2 + 3 == 6 alert ( Math.pow.call ( dummy , 5 , 2) ) // == 5 × 5 == 25
Apply and call are mainly used to perform inheritance, see below.
Objects
For convenience, Types are normally subdivided into primitives and objects. Objects are entities that have an identity (they are only equal to themselves) and that map property names to values, ("slots" in prototype-based programming terminology). JavaScript objects are often mistakenly described as associative arrays or hashes, but they are neither.
JavaScript has several kinds of built in objects, namely Array, Boolean, Date, Function, Math, Number, Object, RegExp and String. Other objects are "host objects", defined not by the language but by the runtime environment. For example, in a browser, typical host objects belong to the DOM (window, form, links etc.).
Creating objects
Objects can be created using a declaration, an initialiser or a constructor function:
// Declaration var anObject = new Object(); // Initialiser var objectA = {}; var objectB = {'index1':'value 1','index2':'value 2'}; // Constructor (see below)
Constructors
Constructor functions are a way to create multiple instances or copies of the same object. JavaScript is a prototype based object-based language. This means that inheritance is between objects, not between classes (JavaScript has no classes). Objects inherit properties from their prototypes.
Properties and methods can be added by the constructor, or they can be added and removed after the object has been created. To do this for all instances created by a single constructor function, the prototype
property of the constructor is used to access the prototype object. Object deletion is not mandatory as the scripting engine will garbage collect any variables that are no longer being referenced.
Example: Manipulating an object
// constructor function function MyObject(attributeA, attributeB) { this.attributeA = attributeA; this.attributeB = attributeB; } // create an Object obj = new MyObject('red', 1000); // access an attribute of obj alert(obj.attributeA); // access an attribute using square bracket notation alert(obj["attributeA"]); // add a new property obj.attributeC = new Date(); // remove a property of obj delete obj.attributeB; // remove the whole Object delete obj;
Inheritance
JavaScript supports inheritance hierarchies through prototyping. For example:
function Base() { this.Override = function() { alert("Base::Override()"); } this.BaseFunction = function() { alert("Base::BaseFunction()"); } } function Derive() { this.Override = function() { alert("Derive::Override()"); } } Derive.prototype = new Base(); d = new Derive(); d.Override(); d.BaseFunction(); d.__proto__.Override(); // mozilla only
will result in the display:
Derive::Override() Base::BaseFunction() Base::Override() // mozilla only
Object hierarchy may also be created without prototyping:
function red() { this.sayRed = function () { alert ('red wine') } } function blue() { this.sayBlue = function () { alert('blue sky') } this.someName = black // inherits black this.someName() // inherits black } function black () { this.sayBlack = function () { alert('black night') } } function anyColour() { this.anotherName = red // inherits red this.anotherName() // inherits red this.sayPink = function() { alert('"Any Colour You Like" is a song of Pink Floyd') } this.anotherName = blue // inherits blue ( + black ) this.anotherName() // inherits blue ( + black ) this.anotherName = 'released 1973' // now it's a string - just for fun } var hugo = new anyColour() hugo.sayRed() hugo.sayBlue() hugo.sayBlack() hugo.sayPink() alert(hugo.anotherName)
Another way to perform inheritance is the use of Function methods apply and call:
function AB ( a , b ) { this.a = a; this.b = b } function CD ( c , d ) { this.c = c; this.d = d } function ABCD ( a , b , c , d ) { AB.apply ( this , arguments ) // inherits constructor AB CD.call ( this , c , d ) // inherits constructor CD this.get = function () { return this.a + this.b + this.c + this.d } } var test = new ABCD ( 'another ' , 'example ' , 'of ' , 'inheritance' ) alert ( test.get () )
Exception handling
Newer versions of JavaScript (as used in Internet Explorer 5 and Netscape 6) include a try ... catch ... finally
exception handling statement. Purloined from the Java programming language, this is intended to help with run-time errors but does so with mixed results.
The try ... catch ... finally
statement catches exceptions resulting from an error or a throw statement. Its syntax is as follows:
try { // Statements in which exceptions might be thrown } catch(error) { // Statements that execute in the event of an exception } finally { // Statements that execute afterward either way }
Initially, the statements within the try block execute. If an exception is thrown, the script's control flow immediately transfers to the statements in the catch block, with the exception available as the error argument. Otherwise the catch block is skipped. Once the catch block finishes, or the try block finishes with no exceptions thrown, then the statements in the finally block execute. This is generally used to free memory that may be lost if a fatal error occurs—though this is less of a concern in JavaScript. This figure summarizes the operation of a try...catch...finally statement:
try { // Create an array arr = new Array(); // Call a function that may not succeed func(arr); } catch (...) { // Recover from error logError(); } finally { // Even if a fatal error occurred, we can still free our array delete arr; }
The finally
part may be omitted:
try { statements } catch (err) { // handle errors }
Whitespace
Spaces, tabs and newlines used outside of string constants are called whitespace. Unlike C, whitespace in JavaScript source can directly impact semantics. Because of a technique called "semicolon insertion", any statement that is well formed when a newline is parsed will be considered complete (as if a semicolon were inserted just prior to the newline). Programmers are advised to supply statement terminating semicolons explicitly to enhance readability and lessen unintended effects of the automatic semicolon insertion.
Unnecessary whitespace, whitespace characters that are not needed for correct syntax, can increase the amount of wasted space, and therefore the file size of .js files. Where file compression techniques that remove unnecessary whitespace are used, performance can be improved if the programmers have included these so-called 'optional' semicolons.
Comments
Comment syntax is the same as in C++.
// comment
/* comment */
See also
References
- David Flanagan, Paula Ferguson: JavaScript: The Definitive Guide, O'Reilly & Associates, ISBN 0596000480
- Danny Goodman, Brendan Eich: JavaScript Bible, Wiley, John & Sons, ISBN 0764533428
- Thomas A. Powell, Fritz Schneider: JavaScript: The Complete Reference, McGraw-Hill Companies, ISBN 0072191279
- Emily Vander Veer: JavaScript For Dummies, 4th Edition, Wiley, ISBN 0764576593