The syntax of JavaScript is a set of rules that defines what constitutes a valid program in

the Javascript language.

Origin of Syntax
Brendan Eich summarized the ancestry of the syntax in the first paragraph of the
JavaScript 1.1 specification as follows:

JavaScript borrows most of its syntax from Java, but also inherits from Awk and Perl, with some
indirect influence from Self in its object prototype system. ”

Variables
Variables in standard JavaScript have no type attached, and any value can be stored in
any variable. Variables can be declared with a var statement. These variables are
lexically scoped and once a variable is declared, it may be accessed anywhere inside the
function where it is declared. Variables declared outside any function, and variables first
used within functions without being declared with 'var', are global. Here is an example of
variable declarations and global values:
x = 0; // A global variable
var y = 'Hello!'; // Another global variable
function f(){
var z = 'foxes'; // A local variable
twenty = 20; // Global because keyword var is not used
return x; // We can use x here because it is global
}
// The value of z is no longer available

Basic data types
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, which JavaScript has no
built-in methods for. For example:
alert(0.94 - 0.01); // displays 0.9299999999999999

although there is only one numeric type in JavaScript 34. but Arrays are a special type of object that has extra behavior and methods specializing in integer indices (e.45e2. (though it is of little use): myNumericWrapper = new Number( 123. the letters A-F may be upper. It is automatically updated if one creates a property with an even larger index.or lowercase In some ECMAScript implementations such as ActionScript. When used as a constructor. Writing a smaller number to the length property will remove larger indices.shapes' ).456" var myNumber = Number( myString ). This length property is the only special feature of Arrays that distinguishes it from other objects. // another floating-point. colorful.setRGB( 0x003366 ). all objects can map from integers to values. Numbers may be specified in any of these notations: 345. Elements of Arrays may be accessed using normal object property access notation: myArray[1]. RGB color values are sometimes specified with hexadecimal integers: var colorful = new Color( '_root. The above two are equivalent.5. equivalent to 345 0377. a numeric wrapper object is created. so it can't be relied upon. // an [[octal]] integer equal to 255 0xFF. The Number constructor may be used to perform explicit numeric conversion: var myString = "123.As a result. // a floating-point number 3. In JavaScript. slice. and push). The toFixed() method is not part of the ECMAScript specification and is implemented differently in various environments.g. Arrays have a length property that is guaranteed to always be larger than the largest integer index used in the array. It's not possible to use the "dot"-notation or strings with alternative representations of the number: .456 ). join. // an "integer". rounding should be used whenever numbers are formatted for output. myArray["1"]. Arrays An Array is a map from integers to values.. // a [[hexadecimal]] integer equal to 255.

as it also works in Mozilla based browsers: .'. or both. world!". {"color":"black".4. // array with length 6 and 6 elements myArray = new Array(365).myArray. // Now h contains 'H' . // this gives you "small" Strings Strings in Javascript are a sequence of characters. "size":"large"}. they are "sparse arrays".2.1. people of Earth. individual characters within a string can be accessed (as strings with only a single character) through the same notation as arrays: var h = greeting[0]. "size":"large"}. dogs["spot"]["size"]. Setting myArray[10] = 'someThing' and myArray[57] = 'somethingOther' only uses space for these two elements. "spot":{"color":"black". // array with length 6 and 4 elements myArray = new Array(0.4. In Mozilla based browsers. "size":"large"}. // not the same as myArray[1] Declaration of an array can use either an Array literal or the Array constructor: myArray = [0. multidimensional. This is the preferred way when accessing individual characters within a string. // an empty array with length 365 Arrays are implemented so that only the elements defined use memory. dog["color"]. var another_greeting = 'Greetings. // this gives you "brown" You can use the object and array declaration literals to quickly create arrays that are associative. "size":"small"}}. cats[0]["size"]. var greeting = "Hello.5).3.. just like any other object. cats = [{"color":"brown".Works in Mozilla based browsers But. You can use the object declaration literal to create objects that behave much like associative arrays in other languages: dog = {"color":"brown". "size":"small"}].1.5]. // this gives you "large" dogs = {"rover":{"color":"brown". Strings in JavaScript can be created directly by placing the series of characters between double or single quotes. // syntax error myArray["01"]. you have to access the individual characters using the charAt() method (provided by String class). The length of the array will still be reported as 58.. for Internet Explorer.1.

This is the basis for JSON. These dictionaries can have any type of value paired with a key.') notation or by a similar syntax to arrays: var name = o. last: "Smith" }. " + x == "hello. set.name. age: 33. purpose: 'This object is utterly without purpose. // contains true var compare2 = ("Hello. which means: of same length and same cases (for alphabets). // Now h contains 'H' . and read individually using the familiar dot ('. Thus: var x = "world". Properties of objects can be created. . // name now contains 'My Object' var answer = o['answer']. hobbies: [ "chess". JavaScript strings are immutable: greeting[0] = "H".charAt(0). which is a string.Works in both Internet Explorer // and Mozilla based browsers however. answer: 42}. // answer now contains 42 Object literals and array literals allow one to easily create flexible data structures: var myStructure = { name: { first: "Mel". // contains false since the // of both operands are // case Now compare1 Now compare2 first characters not of the same Objects The most basic objects in JavaScript act as dictionaries. Objects with values can be created directly through object literal notation: var o = {name: 'My Object'. which is a simple notation that uses JavaScript-like syntax for data exchange. world"). world"). " + x == "Hello. "jogging" ] }. var compare1 = ("Hello.var h = greeting.'. // ERROR Applying the equality operator ("==") to two strings returns true if the strings have the same contents.

var y = 6. var b = ' and that'.Operators The '+' operator is overloaded. document. // z is a string (the digit 4) alert( z + x). // displays 42 alert( +z + x). alert(a + b). // displays 'This and that' // Add two numbers var x = 2. // displays: 1 .write( x ). // displays: 3 x /= 3. x *= 3. alert(x + y). // displays 8 // Adding a string and a number results in concatenation alert( x + '2'). document.// displays 6 Arithmetic Binary operators + * / % Addition Subtraction Multiplication Division (returns a floating-point value) Modulus (returns the integer remainder) Unary operators ++ -- Unary negation (reverses the sign) Increment (can be prefix or postfix) Decrement (can be prefix or postfix) Assignment = Assign += Add and assign -= Subtract and assign *= Multiply and assign /= Divide and assign var x = 1.write( x ). It also has special meaning when used in a regular expression. // displays 22 // Convert a string to a number var z = '4'. // Concatenate 2 strings var a = 'This'. it is used for string concatenation and arithmetic addition and also to convert strings to numbers.

// non-empty string arg = !!arg. In the context of a boolean operation. or one of the special values null. // evaluates to true. a string of length 0. the number 0. // 0. rather than null arg = "finished". same as (Boolean( a ) == false) // evaluates to false. // undefined ). // null ). b = 9.0 ). a = 0. || (logical OR). arg = !!arg. undefined. same as (Boolean( b ) == true) A double use of the ! operator can be used to normalize a boolean value: var arg = null. document. The Boolean function can be used to explicitly perform this conversion: Boolean( Boolean( Boolean( Boolean( Boolean( Boolean( Boolean( false ). or NaN. // displays: 0 Comparison == != > >= < <= Equal Not equal Greater than Greater than or equal to Less than Less than or equal to === !== Identical (equal and of the same type) Not identical Boolean JavaScript has three logical boolean operators: && (logical AND). and ! (logical NOT).x -= 1. // arg is now the value false. // NaN ). // returns returns returns returns returns returns returns false false false false false false false The unary NOT operator ! first evaluates its operand in a boolean context. // arg is now the value true . !b.write( x ). // "" ). // 0 ). and then returns the opposite boolean value: var var !a. all JavaScript values evaluate to true unless the value is the boolean false itself.

>>> Shift right (zero fill) For positive numbers. // returns expr1 if it evaluates to false. a && b is false if a is false.  Short-circuit logical operations means the expression will be evaluated from left to right until the answer can be determined. // returns true if x AND y evaluate to true: (Boolean( x ) == Boolean( y ) == true).In the earliest implementations of JavaScript and JScript. false otherwise x || y. false otherwise In the newer implementations. // returns true if x OR y evaluates to true. There is no reason to evaluate b. in that they always returned a boolean value: x && y. otherwise it returns expr2 This novel behavior is little known even among experienced JavaScripters. >> and >>> yield the same result. For example: a || b is automatically true if a is true. the && and || operators behaved in the same manner as their counterparts in other C derived programming languages. // returns expr1 if it evaluates to true. copies of the leftmost bit (sign bit) are shifted in from the left. and can cause problems if one expects an actual boolean value. otherwise it returns expr2 expr1 || expr2. && || ! and or not (logical negation) Bitwise Binary operators & | ^ And Or Xor << Shift left (zero fill) >> Shift right (sign-propagating). Unary operators ~ String Not (inverts the bits) . these operators return one of their operands: expr1 && expr2. There is no reason to evaluate b.

else if (expr) { statements. case VALUE: statements. For loop for (initial-expr. }  break. expr evaluated after each loopround) { statements.= + += Assignment Concatenation Concatenate and assign Examples str = "ab" + "cd". str += "e". } else if (expr) { statements. break. } . } else { statements. Add a break statement to the end of the last case as a precautionary measure. } Switch statement switch (expr) { case VALUE: statements. // "abcd" // "abcde" Control structures If . cond-expr.. Braces are required. break. since otherwise code execution will continue to the body of the next case block. is optional.    however. Strings can be used for the case values. default: statements.. it's recommended to use it in most cases. in case additional cases are added later. break.

but in practice each browser returns a slightly different set of properties during introspection.. With with(document) { var a = getElementById('a'). While loop while (cond-expr) { statements.. A function may give back a return value.. this is controlled by an internal state property defined by the ECMAscript standard called "DontEnum". In theory. } Do . in loop for (var property-name in object-name) { statements using object-name[property-name]. var c = getElementById('c'). arg3) { statements. .  or the objects at all indices of an array. arg2) { statements.. }  Iterates through all enumerable properties of an object. return expression. }. } Anonymous functions are also possible: var fn = function(arg1.For . There are differences between the various web browsers with regard to which properties will be reflected with the for. arg2. while do { statements. return expression. } while (cond-expr).. function function-name(arg1. var b = getElementById('b').in loop statement.  Note the absence of document. before each getElementById() invocation.. Functions A function is a block with a (possibly empty) parameter list that is normally given a name.

links etc. Objects are entities that have an identity (they are only equal to themselves) and that map property names to values. Function..g. arguments[1].). Number. typical host objects belong to the DOM (window. . Other objects are "host objects". etc. } The number of arguments given when calling a function may not necessarily correspond to the number of arguments in the function definition. Objects For convenience. Creating objects Objects can be created using a declaration.slice(). } else { segmentB -= segmentA.. an initialiser or a constructor function: // Declaration var anObject = new Object(). . For example. form. but they are neither.) are passed by value whereas objects are passed by reference. Math. JavaScript objects are often mistakenly described as associative arrays or hashes. in a browser.. Date.length property. including those beyond the number of named arguments. integers. .sort(). it is not an instance of Array. it does not have methods such as .}. JavaScript has several kinds of built-in objects. a named argument in the definition that does not have a matching argument in the call will have the value undefined. RegExp and String.. Within the function the arguments may also be accessed through the arguments list. defined not by the language but by the runtime environment. ("slots" in prototype-based programming terminology). namely Array. arguments[n]). segmentB) { while (segmentA != segmentB) { if (segmentA > segmentB) { segmentA -= segmentB. arguments[0]. Types are normally subdivided into primitives and objects. Example: Euclid's original algorithm of finding the greatest common divisor. Note that while the arguments list has a . (This is a geometrical solution which subtracts the shorter segment from the longer): function gcd(segmentA. } } return segmentA. Basic data types (strings. Boolean. this provides access to all arguments using indices (e. . Object.

// access an attribute using square bracket notation alert(obj["attributeA"]). // remove the whole Object delete obj. Properties and methods can be added by the constructor.'index2':'value 2'}. This means that inheritance is between objects.// Initialiser var objectA = {}. not between classes (JavaScript has no classes). Objects inherit properties from their prototypes. this. attributeB) { this. JavaScript is a prototype based object-based language. or they can be added and removed after the object has been created. } // create an Object obj = new MyObject('red'.Override = function() { alert("Base::Override()"). var objectB = {'index1':'value 1'. 1000). To do this for all instances created by a single constructor function. // remove a property of obj delete obj. // add a new property obj. . the prototype property of the constructor is used to access the prototype object.attributeC = new Date().attributeA). Object deletion is not mandatory as the scripting engine will garbage collect any variables that are no longer being referenced.attributeA = attributeA. // access an attribute of obj alert(obj.attributeB = attributeB. Inheritance JavaScript supports inheritance hierarchies through prototyping. // Constructor (see below) Constructors Constructor functions are a way to create multiple instances or copies of the same object.attributeB. For example: function Base() { this. Example: Manipulating an object // constructor function function MyObject(attributeA.

d. Derive.Override = function() { alert("Derive::Override()"). this. } Base. d. } // Derived class. will result in the display: Derive::Override() Base::BaseFunction() Another way to implement the override method is: // Base class.prototype. } } Derive. Derive. d = new Derive(). function Base(paramA) { this.Override = function() { alert("Base::Override()").paramA = paramA.paramB = paramB.prototype. function Derive(paramA.prototype = new Base(). } this.BaseFunction = function() { alert("Base::BaseFunction()").parent(paramA). } .} } this.BaseFunction().Override().BaseFunction = function() { alert("Base::BaseFunction()").Override = function() { alert("Derive::Override()"). } Base. } function Derive() { this.parent = Base.prototype. paramB) { this.prototype = new Base().

Otherwise the catch block is skipped.. then the statements in the finally block execute..catch. 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.Override(). the script's control flow immediately transfers to the statements in the catch block. or the try block finishes with no exceptions thrown.. This figure summarizes the operation of a try. we can still free our array delete arr.BaseFunction(). If an exception is thrown. catch . } catch (. d...... } The finally part may be omitted: try { statements } catch (err) { // handle errors } ... d.. // Call a function that may not succeed func(arr). The try . with the exception available as the error argument.. Once the catch block finishes. the statements within the try block execute.. } finally { // Even if a fatal error occurred. Exceptions Newer versions of JavaScript (as used in Internet Explorer 5 and Netscape 6) include a try . catch .d = new Derive(). 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.) { // Recover from error logError().finally statement: try { // Create an array arr = new Array(). finally statement catches exceptions resulting from an error or a throw statement. finally exception handling statement to handle run-time errors..

They follow a syntax similar to that used in Java: try { catch catch catch catch statement. Unlike C. tabs and newlines used outside of string constants are called Whitespace. even if you don't need to handle the error: try { statement. It is an error to simply use the try block alone. } ( e if e == "InvalidEmailException" ) { statement. as an extension to the ECMAScript standard. This compression will work far better than any whitespace parser and will reduce the size . Unnecessary whitespace. The easiest way to address the problem of file size is to set the server to use zip compression. } catch( ) { statement. Programmers are advised to supply statement terminating semicolons explicitly to enhance readability and lessen unintended effects of the automatic 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). Whitespace and semicolons Spaces. whitespace characters that are not needed for correct syntax.js files. even if you don't need to use it: try { statement. It is common to start object names with a capitalised letter and functions or variables with a lower-case letter. and therefore the file size of . } ( e if e == "InvalidIdException" ) { statement. the catch part may also be omitted: try { statements } finally { // ignore potential errors and just go directly to finally } Note that at least one of catch and finally are required. } ( e if e == "InvalidNameException" ) { statement. } ( e ) { statement. } // ERROR The Mozilla implementation allows for multiple catch statements. can increase the amount of wasted space. } Miscellaneous Case sensitivity JavaScript is case sensitive.In fact. } // ERROR The catch argument is also required. Because of a technique called "semicolon insertion". whitespace in JavaScript source can directly impact semantics.

// comment /* multi-line comment */ .of all other source your server uploads. This method will work with or without semicolons. Comments Comment syntax is the same as in C++.