You are on page 1of 31


Javascript code is a scripting language designed for use within a web page and/or on a web server. It is used to create special effects within a web page. Elements such as links, images and forms can all be manipulated using this powerful technology. Unlike CGI scripts, javascript codes can be placed directly into your HTML code. It can also reside on your server and be called from a small code within your web page. If you'd like to place your javascript code within a file on your server, you will need to open a plain text editor and place your javascript code within the editor. The javascript code file should then be saved with a .js extension. In order to call your javascript code, you will need to link to the file. You can do so by placing a small javascript code within the HTML of your web page that looks something like this: <SCRIPT language="Javascript" src=""> This powerful scripting language can be used to create special effects within your web page, such as link effects, mouseovers, image roll overs, navigational systems and much more.

JavaScript syntax

The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program. The examples below make use of the alert function for standard text output. The JavaScript standard library lacks an official standard text output function. However, given that JavaScript is mainly used for client-side scripting within modern web browsers, and that almost all web browsers provide the alert function, alert is used in the examples.

Brendan Eich summarized the ancestry of the syntax in the first paragraph of the JavaScript 1.1 specification[1] 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.

[edit] Basics

[edit] Case sensitivity
JavaScript is case sensitive. It is common to start the name of a constructor with a capitalised letter, and the name of a function or variable with a lower-case letter.

[edit] Whitespace and semicolons
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", some statements that are 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, although it degrades readability, because it may lessen unintended effects of the automatic semicolon insertion. [2]
return a + b; // Returns undefined. Treated as: // return; // a + b;

a = b + c (d + e).foo() // Treated as: // a = b + c(d + e).foo();

[edit] Comments
Comment syntax is the same as in C++ and many other languages.
// a short, one-line comment /* this is a long, multi-line comment about my script. May it one day be great. */ /* Comments /* may not be nested */ Syntax error */

[edit] Variables
Variables in standard JavaScript have no type attached, and any value can be stored in any variable. Variables are declared with a var statement, multiple variables can be declared at once. An identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase). Starting with JavaScript 1.5, ISO 8859-1 or Unicode letters (or \uXXXX Unicode escape sequences) can be used in

identifiers.[3] In certain JavaScript implementations, the at sign (@) can be used in an identifier, this is contrary to the specifications and not supported in newer implementations. Variables are lexically scoped and once a variable is declared, it may be accessed anywhere inside the function where it is declared, even before the declaration appears. In effect, variable declarations are hoisted or lifted to the top of the enclosing function, but a variable value will still be undefined until it is initialized. Variables declared outside any function are global. If a variable is declared in a higher scope, it can be accessed by child functions. Here is an example of variable declarations and global values: var x = 0; // A global variable, because it is not in any function function f() { var z = 'foxes', r = 'birds'; // 2 local variables
m = 'fish'; // global because it wasn't declared anywhere before function child() { var r = 'monkeys'; // This variable is local and does not affect the "birds" r of the parent function. z = 'penguins'; // The child function is able to access the variables of the parent function, this is called closure. } twenty = 20; // This variable is declared on the next line, but usable anywhere in the function, even before, as here var twenty; child(); return x; // We can use x here because it is global } f(); alert(z); // This line will raise a ReferenceError exception because the value of z is no longer available

When JavaScript tries to resolve an identifier, it looks in the local function scope. If this identifier is not found, it looks in the outer function that declared the local one, and so on along the scope chain until it reaches the global scope where global variables reside. If it is still not found, Javascript will raise a ReferenceError exception. When assigning an identifier, Javascript does the exact same process to retrieve this identifier, except that if it is not found in the global scope, it will create the "variable" as a property of the global object.[4] As a consequence, a variable never declared will be global if assigned. Declaring a variable (with the keyword var) in the global code (i.e. outside of any function body), assigning a never declared identifier or adding a property to the global object(usually window) will also create a new global variable. Note that JavaScript's strict mode forbids the assignment of an undeclared variable, which avoids global namespace pollution.

[edit] Primitive data types

// unenforced type during check. displays true alert(undefined === null). In a Boolean context.. displays undefined alert(undefined == null).. // .. calling isUndefined(my_var) raises a ReferenceError if my_var is an unknown identifier. because in versions before ECMAScript 5. . null is considered an object by typeof.. // .. Note: Undefined is considered a true primitive-type. [edit] Null Unlike undefined.myProp). or that one Here. function isUndefined(x) { return x === void 0. Functions like this won't work as expected: function isUndefined(x) { var u. Thus (x == undefined) is not a foolproof way to check whether a variable is undefined. and is also returned when checking for object properties that do not exist. null is often set to indicate that something has been declared but has been defined to be empty.. } // . defined. the null value will not equal other false types. return x === u. . // testObj exists. Surprisingly. As such.. var test. Some of the primitive data types also provide a set of named values that represent the extents of the type boundaries. it is legal for someone to write var undefined = "I'm defined now". [edit] Undefined The value of "undefined" is assigned to all uninitialized variables. A more robust approach is to compare using (typeof x === 'undefined')... . As such. } // like this. when performing checks that enforce type checking. These named values are described within the appropriate sections below. the undefined value will not equal other false types.. set to value of undefined Note: There is no built-in language literal for undefined.The JavaScript language provides a handful of primitive data types. displays undefined alert(testObj.. displays false // variable declared but not defined.. when performing checks that enforce type checking.. // enforce type during check.. // . whereas typeof my_var === 'undefined' doesn't. Note: Null is a true primitive-type within the JavaScript language.. var testObj = {}. the value of null is considered a false value in JavaScript.. property does not.. alert(test). // test variable exists but value not . of which null (note case) is the single value. the undefined value is considered a false value. In a Boolean context.

94 . // .5.9299999999999999 As a result. This becomes an issue when comparing or formatting numbers. or a unary + or -. . For example: alert(0. also returned as a failure in . The Number constructor. // displays 0. alert(typeof null === 'object'). When used as a constructor. displays // enforce type during check. . var myNumber2 = +myString. // // an "integer"... −∞ and NaN (Not a Number) of the number type may be obtained by two program expressions: Infinity. // displays false alert(0. including fractions.. digits represented by the . a routine such as the toFixed() method should be used to round numbers whenever they are formatted for output. instance) NaN. a numeric wrapper object is created (though it is of little use): myNumericWrapper = new Number(123.456).01). Numbers may be specified in any of these notations: 345.45e2. equivalent to 345 an octal integer equal to 255 a hexadecimal integer equal to 255. string-to-number conversions These three special values correspond and behave as the IEEE-754 describes them. var myNumber1 = Number(myString).2 + 0. true alert(null === undefined). they do not always exactly represent real numbers.3)... // JavaScript 34.. may be used to perform explicit numeric conversion: var myString = "123. // Positive Infinity (negative obtained with -Infinity for // The Not-A-Number value. which provides an accuracy nearly 16 significant digits. displays false // true [edit] Number Numbers are represented in binary as IEEE-754 Doubles. // 3.. // 0377. Because they are floating point numbers.0. // 0xFF.456". // unenforced type during check.alert(null == undefined). letters A-F may be upper or lowercase The extents +∞..1 == 0. although there is only one numeric type in a floating-point number another floating-point.

. . world").'." //Not good.charAt(0). In JavaScript strings can be created directly by placing the series of characters between double or single quotes. which means: of same length and same cases (for alphabets). // Now compare1 contains true var compare2 = ("Hello. var x = ""Hello. " +x == "hello. " +x == "Hello. var anotherGreeting = 'Greetings...[edit] String A string in Javascript is a sequence of characters.. var compare1 = ("Hello. var x = '"Hello.. . // // // // case . 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]..prototype). world!" he said. world!". var greeting = "Hello. This is the preferred way when accessing individual characters within a string. world!" he said." //That works by replacing " with \" It is possible to create a string using the String constructor: var greeting = new String("Hello... // Now compare2 contains .. world"). false since the . In Modern browsers. of both operands . These objects have a valueOf method returning the primitive string wrapped into them: . var x = "\"Hello.. // Not Working Applying the equality operator ("==") to two strings returns true if the strings have the same contents. world!\" he said. But JavaScript strings are immutable: greeting[0] = "H". world!"). people of Earth...' //Just fine... .. first characters .. are not of the same You cannot use quotes of the same type inside the quotes unless they are escaped. You can access individual characters within a string using the charAt() method (provided by String. Thus: var x = "world". as it also works in nonmodern browsers: var h = greeting.

Some experts[6] use the terms "truthy" and "falsy" to describe how values of various types behave when evaluated in a logical context. The complement evaluates as true. When used in a logical context. The typeof operator returns the string "boolean" for these primitive types. this value is rounded to nearest Number type value.valueOf(). NaN. Automatic type coercion by the equality comparison operators ( == and !=) can be avoided by using the type checked comparison operators. undefined. // Is 'string' Equality between two String objects does not behave as with string primitives: var s1 = new String("Hello !"). JavaScript converts String. Boolean. // Is false. The left–operand is returned if it can be evaluated as: false. because they are two distinct objects s1. var s2 = new String("Hello !"). The binary logical operators returned a Boolean value in early versions of JavaScript.valueOf() == s2. a runtime error is generated. // Is 'object' typeof s. using the . First. Number. but now they return one of the operands instead. An expression can be . null. otherwise the right–operand is returned.toString() methods of the object. or objects that can be evaluated as such a string) because the boolean operand will be compared as a numeric value. If this fails. ( === and !==). typeof s. "false" and any object (except null). Object If an object is compared with a number or string. // Is true [edit] Boolean JavaScript provides a Boolean data type with true and false literals. a mathematical value is derived from the string numeric literal. s1 == s2. 0.valueOf() or .var s = new String("Hello !"). An object is converted to a primitive String or Number value. in the case of conjunction (a && b). Boolean If one of the operands is a Boolean. including the strings "0". or Object operands as follows:[5] Number and String The string is converted to a number value. the Boolean operand is converted to 1 if it is true or to 0 if it is false. Automatic type coercion by the comparison operators may differ for cases of mixed boolean and number-compatible operands (including strings that can be evaluated as a number. JavaScript attempts to return the default value for the object. JavaScript attempts to convert the string numeric literal to a Number type value. and the empty string ("") evaluate as false due to automatic type coercion. in the case of disjunction (a || b). Next. This may be unexpected. When type conversion is required. -0. or true. especially in regard to edge cases.valueOf().

alert(true === !!0).. using the Boolean() function. // false.... var b = new Boolean(false). null // true. // false. true → 1 === 1 ← alert(false == alert(true == 0 ).. false → 0 !== 2 ← 1 ).... // true.toString(). the typeof operator does not return "boolean" for the object wrapper..... // true. a method such as .... true → 1 === 1 ← "1" alert(false == alert(false == alert(false == "0"). //Automatic type coercion alert(true == 2 )..valueOf(). must be used to retrieve the wrapped value.. false → 0 !== NaN //Type checked comparison (no conversion of types and values) alert(true === 1).. // true. For explicit coercion to the Boolean type. data types match but values differ ? true : false). or using the conditional operator (c ? t : f)...explicitly cast to a boolean primitive by: doubling the logical negation operator (!!).. true → 1 !== 2 ← "2" alert(false == alert(true == "2"). alert( 1 numbers alert("0" ? true : false). // false... all objects are “truthy” except // true. only ±0 and NaN are “falsy” The new operator can be used to create an object wrapper for a Boolean primitive. false → 0 !== 2 ← "2" "1"). // false. it returns "object". // false.. // true. // true. Because all objects evaluate as true. data types and values match // false. // true. data types do not match //Explicit type coercion alert(true === !!2). However. only the empty string is “falsy” alert(Boolean({})).. false → 0 === 0 ← "0" "" ). true → 1 !== 2 ← 2 2 1 0 alert(false == alert(true == 2 )...... false → 0 === 0 ← "2"). false → 0 === 0 ← "" NaN)...... // Object false {} . or .... // true... Mozilla recommends that the Boolean() function (without new) be used in preference to the Boolean object.. // false.

var myArray = []. // Point the variable myArray to a Arrays have a length property that is guaranteed to always be larger than the largest integer index used in the array. are prototyped with methods and properties to aid the programmer in routine tasks (e.valueOf()). // Equivalent to alert("hello world").. // Preferred if (0 || -0 || "" || null || undefined || b. } else if ([] && {} && b && typeof b === "object" && b... // Boolean true var f = Boolean(b. JavaScript environment notwithstanding.valueOf()).. // Fill the next empty index. . It is automatically updated if one creates a property with an even larger index.valueOf() || !new Boolean() || !t) { alert("Never this"). JavaScript native objects are considered part of the JavaScript specification. Writing a smaller number to the length property will remove larger indices.. As in the C family. newly . in this case 0 alert(myArray[0]). } [edit] Native objects The JavaScript language provides a handful of native objects. // Boolean false var n = new Boolean(b). this set of objects should always be available. // Not recommended n = new Boolean(b.push("hello world").g. [edit] Array An Array is a JavaScript object prototyped from the Array constructor specifically designed to store data values indexed by integer keys. join. unlike the basic Object type.var t = Boolean(b). and push). Arrays. created. empty Array myArray. arrays use a zero-based indexing scheme: A value that is inserted into an empty array by means of the push method occupies the 0th index of the array.toString() === "false") { alert("Always this"). // . slice.

1.Elements of Arrays may be accessed using normal object property access notation: myArray[1].. // results in "brown" dog. size: "small"}]. dog["color"]. size: "large"}. One can use the object declaration literal to create objects that behave much like associative arrays in other languages: dog = {color: "brown".. cats[0]["size"]. but one can mimic them with arrays-of-arrays. including 2 undefined elements myArray = new Array(0. // not the same as myArray[1] Declaration of an array can use either an Array literal or the Array constructor: myArray = [0. The length of the array will still be reported as 58. size: "large"}. dogs["spot"]["size"]. // results in "large" dogs = {rover: {color: "brown". {color: "black".color. 4. 1. It's not possible to use the "dot"-notation or strings with alternative representations of the number: myArray.color. // an empty array with length 365 Arrays are implemented so that only the elements defined use memory. Setting myArray[10] = 'someThing' and myArray[57] = 'somethingOther' only uses space for these two elements. 4. // results in "brown" [edit] Date . // array with length 6 and 6 // . 3. or both. multidimensional. The above two are equivalent. .. spot: {color: "black". // syntax error myArray["01"].. elements. size: "large"}. // results in "small" dogs.rover. they are "sparse arrays". (Technically. 2. // the 2nd item in myArray myArray["1"]. . 5].1.) cats = [{color: "brown". 5). // also results in "brown" One can use the object and array declaration literals to quickly create arrays that are associative. size: "small"}}. just like any other object. JavaScript does not support multidimensional arrays. // array with length 6 and 6 elements myArray = new Array(365). .

getSeconds()).getMonth()+1) + '-' + d. 30). 2. 14. There are several ways of providing arguments to the Date constructor. Custom error messages can be created using the Error class: throw new Error("Something went wrong. Nested within conditional statements. unlike Array or Date. new Date() // representing the current time/date. // 2010-Mar-01 14:25:30 // Displays '2010-3-1 14:25:30': alert(d.getDate() + ' ' + d.getHours() + ':' + d. such instantiations can substitute for try/catch blocks: var emailAddress = prompt("Please enter your e-mail address:". as well as a useful toString: var d = new Date(2010. 14. 1. // Built-in toString returns something like 'Mon Mar 01 2010 14:25:30 GMT-0500 (EST)': alert(d). new Date(2010.")."). } [edit] Math The Math object contains various math-related constants (e. 25. 2. create a new Date instance create a new Date instance create a new Date instance create a new Date instance from Methods to extract fields are provided. cosine). if (!emailAddress || emailAddress. 30) // representing 2010-Mar-01 14:25:30 new Date("2010-3-1 14:25:30") // a String.g.A Date object stores a signed millisecond count with zero representing 1970-01-01 00:00:00 UT and a range of ±108 days. 25. 1) // representing 2010-Mar-01 00:00:00 new Date(2010. (Note the "Math" object has no constructor.getMinutes() + ':' + d. All its . 1. [edit] Error This section requires expansion.getFullYear() + '-' + (d. π) and functions (e. Note that months are zero-based. 2.g.length == 0) { throw new Error("Excuse me: You must enter your e-mail address to continue. "").

PI Math.7183 0. -2) Math.78540 rad.69315 2.7) Math.cos(Math.4142 e: Euler's number Natural logarithm of 2 Natural logarithm of 10 Logarithm to the base 2 of e Logarithm to the base 10 of e π: circumference/diameter of a circle Square root of ½ Square root of 2 Property Math.E) Math.70711 2.atan2(-3.max(1.floor(1. base e Maximum: (x > y) ? x : y Minimum: (x < y) ? x : y .) All the trigonometric functions use angles expressed in radians.SQRT1_2) Math.SQRT1_2 Math.acos(Math.min(1.log(Math.4427 0.methods are "static" aka "class" methods.78540 rad.LN10 Math.asin(Math.SQRT2 Example Math.1) Math. Arcsine = 45° 0.9) Math.3562 rad.3) Math.LOG2E Math. = Whole circle arctangent (-π to +π) -135° 2 0.abs(-2.atan(1) Math.3026 1.70711 1. Properties of the Math object Value Returned Description rounded to 5 digits 2.E Math.43429 3.exp(1) Math.7.7183 1 1 1 -2 Ceiling: round up to smallest integer ≥ argument Cosine Exponential function: e raised to this power Floor: round down to largest integer ≤ argument Natural logarithm. -3.LOG10E Math.PI/4) Math. not degrees or grads.14159 0.SQRT1_2) Math.ceil(1. Half circle arctangent (-π/2 to +π/2) = 45° -2. Arccosine = 45° 0. -2) Methods of the Math object Value Returned Description rounded to 5 digits 2.LN2 Math.3 Absolute value: (x < 0) ? -x : x 0.78540 rad.

"string".9 .alphanumeric .test('Tom')) alert('Format OK'). (/\w\w\w/...test('1')) alert('Odd number').sqrt(49) Math.replace(/Tom/.test('B')) alert('Letter'). "string".PI/4) Math.sin(Math.test("My name is Tom")) alert("Hello Tom!").tan(Math.test(string).5 rounds to 2) Sine Square root Tangent [edit] Regular Expression Main article: Regular expression /expression/.. // Here are some examples if(/Tom/. (letters before Tom) alert("My name is Tom".Math.replace(/expression/. (/\S\S\s\S\S\S\S/.replacement).test('5')) alert('Digit'). (/[a-zA-Z]/. y) gives x Pseudorandom number between 0 (inclusive) and 1 (exclusive) Round to the nearest integer..Z a. (/[13579]/.5) Math.test('My name')) alert('Format OK'). alert("My name is Tom".search(/expression/).test('B')) alert('Big letter').17068 2 0.test('0')) alert('Digit'). Character matching: // A. 1.PI/4) 9 0..random() Math."John")). (/[a-z]/. half fractions are rounded up (e.g. 2) Math. (/[A-Z]/.test('b')) alert('Small letter').pow(x.pow(-3.round(1. name is John" // == 11 // == "My Character Classes: // // // // // // // // // if if if if if if if if \d \D \s \S \w \W [ ] [^ ] digit non digit space non space word char non word one of one not of range (/\d/.search(/Tom/)).70711 7 1 Exponentiation (raised to the power of): y Math.z 0. (/[0-9]/..

.test("abc")) "abbbc" Anchors: // ^ // $ ..allow matches to span multiple lines .\xFF \t \n \r .string starts with . "abbbc" etc. Repeaters: // // // // // // // ? * + {n} {n.. alert("OK").range n to m alert("OK"). if (/ab{1.test("My name is Tom")) Subexpression // ( ) . // match: "abc".test("abbbc")) if (/ab{3. Tam or Tim').3}c/.0 or 1 match . "abbbbbc" etc.test('Tom')) alert ('Hi Tom. if (/^My/. // match: "ac". // match: "abbbc".exactly n . // match: "abbbc" alert("OK"). if (/ab{3}c/.test("My name is Tom")) if (/Tom$/.\uFFFF \x00. // alert("Hi Tom or John!").test("abc")) "abbbc" etc.n or more . if (/water(mark)?/.test("abbbc")) "abbbbc".// // // // // // // \ ."abbc". "abbc".} {0.test("watermark")) match: "water".0 or more .test("John")) Flags: // /g // /i // /m .m} . alert("OK"). alert("OK").. "watermark".string ends with alert ("Hi!"). "abc" alert("OK"). "abc".test("ac")) if (/ab*c/.n} {n.n or less .}c/. // match: "ac". alert ("Hi Tom!").test("A")) alert ('A or B'). if (/ab?c/.test("ac")) "abbc". | - Unicode hexadecimal ASCII hexadecimal tab new line CR any character OR if (/T.m/. // match: "abc". if (/A|B/.ignore upper/lower case .1 or more . if (/ab+c/. if (/(Tom)|(John)/.groups characters alert("Here is water!").

which is the last in the argument list."12:15". //3 A function instance has properties and methods.split(". 'return x+y'). 12:15 and 16:45". } else alert("Did not find a valid date!").cat. // == "hi John!" // == "ratutam" // == "ratutum" Advanced methods my_array = my_string. function subtract(x."John"))."cat". // First group == "2009-09-08" var my_time = results[2]. 'y'. // example my_array = "dog.replace(/Tom/i. var results = myRe. y) { return x + y. // example my_array = "We start at 11:30. my_array==("dog". // Second group == "09:37:08" alert("It is " + my_time + " on " + my_date). } var t = add(1. y) { . var add = new Function('x'.replace(/ta/g.exec("The date and time are 2009-09-08 09:37:08. as this pattern is faster and more intuitive.")."16:45"). // Entire match var my_date = results[1].y is the argument."tu")). //3 The add function above is often defined using the following pattern."tu")).match(/\d\d:\d\d/).alert("hi tom!"."cow")."). // my_array = my_string. function add(x.match(my_expression). if (results) { alert("Matched: " + results[0]). // my_array=("11:30". alert("ratatam". var t = add(1. [edit] Function Every function in Javascript is an instance of the Function object: //x. alert(t).split(my_delimiter). 2). 2).cow". alert(t). Capturing groups var myRe = /(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})/. 'return x+y' is the function body.replace(/ta/. alert("ratatam".

return x . // string results in concatenation displays 22 displays $34. // + 3 + 4).y. // + (3 + 4)). // displays: 3 alert(x--). alert(++x).y. } alert(subtract. y) { return x . } */ [edit] Operators The '+' operator is overloaded: it is used for string concatenation and arithmetic addition. x becomes 2 then . alert(subtract. // displays true alert(+'Hello').expected amount of arguments.length). // displays Hello // Add two numbers alert(2 + 6). // displays 8 // Adding alert(2 + alert('$' alert('$' a number and a '2'). // displays: 2 alert(x++). // Concatenate 2 strings alert('He' + 'llo'). it can convert a numeric string to a number. // displays NaN [edit] Arithmetic JavaScript supports the following binary arithmetic operators: + * / % Addition Subtraction Multiplication Division (returns a floating-point value) Modulus (returns the integer remainder) JavaScript supports the following unary arithmetic operators: + ++ -Unary conversion of string to number Unary negation (reverses the sign) Increment (can be prefix or postfix) Decrement (can be prefix or postfix) var x = 1. /* function subtract(x. x becomes 3 then alert(x). // displays: 3. As a unary operator. // displays: 2.toString()).//2. This may cause problems when inadvertently mixing strings and numbers. but $7 may have been expected displays $7 // Convert a string to a number alert(+'2' === 2).

var a.// obj_3 is a reference to obj_2 obj_2. // alert(--x).a). b. // displays: 3 // displays: 1 // displays: 0 Assignment of object types var obj_1 = {a: 1}. alert(x).a + " " + obj_2.a = 7. The left hand side of an assignment is a pattern that resembles an arbitrarily nested object/array literal containing l-lvalues at its leafs which are to receive the substructures of the assigned value. // displays 1 1 2 obj_2. alert(x). // displays 1 2 2 obj_2 = obj_1. b] = [3.a).a + " " + obj_2.a = 2.a). x -= 1. d. 4]. x /= 3. var arr = []. // displays 7 7 2 [edit] Destructuring Assignment In Mozilla's JavaScript. since version 1.a + " " + obj_3.// modifies obj_1 alert(obj_1. c.a + " " + obj_3.a + " " + obj_2. alert(a + '.7. // displays: 2 displays: 1 [edit] Assignment = += -= *= /= %= Assign Add and assign Subtract and assign Multiply and assign Divide and assign Modulus and assign Assignment of primitive types var x = 1.// obj_2 now references obj_1 // obj_3 now the only reference to what was obj_2 alert(obj_1. bar: 6. 'Content']}. x *= 3.alert(x). e. // displays: 3. var obj_3 = obj_2. baz: ['Baz'. var obj_2 = {a: 0}. alert(obj_1.' + b). [a. destructuring assignment allows the assignment of parts of data structures to several variables at once. .a + " " + obj_3. alert(x).4 e = {foo: 5.

' + b). a]. == obj2). obj1. any expression evaluates to true except the following: Strings: Numbers: Special: Boolean: "". // swap contents of a and b alert(a + '. null. NaN. The Boolean function can be used to explicitly convert to a primitive of type Boolean: // Only empty strings return false alert(Boolean("") === false).' + b + '. [edit] Logical JavaScript provides four logical operators: unary negation (NOT = !a) binary disjunction (OR = a || b) and conjunction (AND = a && b) ternary conditional (c ? t : f) In the context of a logical operation. ''. even if the values of them are the same. // displays: 5. alert(a + '.6. foo: a. bar: b}) = e..Content [a. -0.Baz. 0. undefined. arr[3]]..' + arr). . //false //true See also String. b] = [b.({baz: [arr[0]. false. == obj1).5 [edit] 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 When comparing variables which are objects they are considered to be different if their objects are not the same object. {a: 1}. // displays: 6. so: var obj1 = var obj2 = var obj3 = alert(obj1 alert(obj3 {a: 1}.

alert(!1 === Boolean(!1)). // These types return false alert(Boolean(null) === false). alert([2]? alert("2" != true). alert(Boolean(!"") === !!"s"). alert(Boolean(0) === !1). // Only zero and NaN return false alert(Boolean(NaN) === false). // "0" → 0 … (0==0) … 0 true : false). alert(Boolean("") === !"s"). alert(Boolean(!0) === !!1). // [0]. have an anticipated side effect. alert(Boolean(0) === false). alert(Boolean(-0) === false). // "1" → 1 … (1==1) … 1 true : false). alert([] ? comparison uses []. alert(!"" === Boolean(!"")). alert([1]? alert("1" == true). alert(!!1 === Boolean(1)).toString() alert([0] == false). and returns the negation. The ternary operator can also be used for explicit conversion: alert([] == false). alert(Boolean([]) === true). explicitly converts an expression to a primitive of type Boolean: alert( !0 === Boolean(!0)). (i++). the right operand is only executed if the left operand does not suffice to determine the value of the expression.toString() == "0" true : false).toString() == "1" true : false). alert(!"s" === Boolean(!"s")). alert(!!"s" === Boolean("s")).alert(Boolean("false") === true). alert("2"? ← true true : false). alert([0]? alert("0" == false). alert("1"? ← true alert([2] != true). // "2" → 2 … (2!=1) … 1 Expressions that use features such as post–incrementation. // equivalent to -1*0 alert(Boolean(-2) === true ). Using the operator twice in a row. alert("0"? ← false alert([1] == true). // [1]. alert(!!0 === Boolean(0)).toString() == "2" true : false). alert(!!"" === Boolean("")). // “truthy” but the true : false). // equivalent to Boolean() The NOT operator evaluates its operand as a Boolean. alert(Boolean(undefined) === false). as a double negative. JavaScript provides short-circuit evaluation of expressions. // All objects return true alert(Boolean(this) === true). alert(Boolean("0") === true). // [2]. alert(Boolean({}) === true). .

there is no reason to evaluate b. there is no reason to evaluate f. return a. return a. otherwise return b Programmers who are more familiar with the behavior in C might find this feature surprising but it allows for a more concise expression of patterns like null coalescing: var s = t || "(default)". all contemporary implementations return one of their operands instead: alert(a || b). // if a is false. otherwise return b alert(a && b). >> and >>> yield the same result. // if a is true. JavaScript supports the following unary bitwise operators: ~ Not (inverts the bits) [edit] String = + += Assignment Concatenation Concatenate and assign Examples . [edit] Bitwise This section requires expansion. However. // assigns t. copies of the leftmost bit (sign bit) are shifted in from the left. >>> Shift right (zero fill) For positive numbers. In early versions of JavaScript and JScript. JavaScript supports the following binary bitwise operators: & | ^ And Or Xor << Shift left (zero fill) >> Shift right (sign-propagating). alert(a && b). alert(c ? t : f). // When a is true. // When c is true. // When a is false. there is no reason to evaluate b. the binary logical operators returned a Boolean value (like most C–derived programming languages). or the default value if t is null. etc.alert(a || b). empty.

} Unlike the if statement.. not "4" or 4. [edit] If . } [edit] Conditional operator The conditional operator creates an expression that evaluates as one of two expressions depending on a condition.str = "ab" + "cd". I. the conditional operator cannot omit its "else-branch".e. is the same as: if (condition) { result = expression. [edit] Control structures [edit] Compound statements A pair of curly brackets { } and an enclosed sequence of statements constitute a compound statement. [edit] Switch statement The syntax of the JavaScript Switch statement is as follows: switch (expr) { case SOMEVALUE: //statements. } else if (expr2) { //statements. else if (expr) { //statements.. } else { result = alternative. break. } else { //statements. result = condition ? expression : alternative. which can be used wherever a statement can be used. This is similar to the if statement that selects one of two statements to execute depending on a condition.. str2 = "2"+2 // "abcd" // "abcde" // "22". str += "e". the conditional operator is to expressions what if is to statements. .

loop statement) { /* statements will be executed every time the for{} loop cycles. There are differences between the various web browsers with regard to which properties will be reflected with the for. in case additional cases are added later.. is optional. in loop The syntax of the JavaScript For . Braces are required. Expressions can be used instead of ANOTHERVALUE: //statements. Iterates through all used indices of array including all user-defined properties of array object if any.. Strings literal values can also be used for the case values. Add a break statement to the end of the last case as a precautionary measure. however. [edit] For loop The syntax of the JavaScript for loop is as follows: for (initial.. since otherwise code execution will continue to the body of the next case block. it is usually needed.. } Iterates through all enumerable properties of an object. In theory. default: //statements. condition. break. break. while the condition is satisfied */ } or for (initial. in loop is as follows: for (var property_name in some_object) { //statements using some_object[property_name].. } break. this is controlled by an internal state property defined by the ECMAscript standard called "DontEnum". case default: is optional. loop statement) // one statement [edit] For . loop statement. Thus it may be better to use a traditional for loop with a numeric index when iterating over arrays. but in practice each browser returns a slightly different set .

[edit] Labels JavaScript supports nested labels in most implementations. }. [edit] With The with statement sets the default object for the set of statements that follow. while loop is as follows: do { statement1. } [edit] Do . loops or blocks can be labeled for the break statement... [edit] While loop The syntax of the JavaScript while loop is as follows: while (condition) { statement1. statement3.. .. Although goto is a reserved word. before each getElementById() invocation.[7] it does not work in JavaScript. statement2... loop1: for (var a = 0... adding a method to the array prototype with Array.. in loops to loop over the method's name. Thus.. a < 10.} may cause for . Note the absence of document. and loops for continue.of properties during introspection. var b = getElementById('b'). } while (condition). var c = getElementById('c')..newMethod = function() {. . a++) { . while loop The syntax of the JavaScript do . It is useful to test for a given property using if (some_object. statement3.. The semantics are similar to the with statement of Pascal.prototype. }.. with (document) { var a = getElementById('a')..hasOwnProperty(property_name)) { . statement2.

function gcd(segmentA. 40)). b < 10. The number of arguments given when calling a function may not necessarily correspond to the number of arguments in the function definition. -diff). Within the function. this provides access to all arguments using indices (e. // Continues the first loop. // 20 Functions are first class objects and may be assigned to other variables. the arguments may also be accessed through the arguments object. // 20 var mygcd=gcd. segmentB) { var diff = segmentA .segmentB. loop2: for (var b = 0. return diff > 0 ? gcd(segmentB. } alert(gcd(60. } alert('finished') } block1: { alert('hello'). arguments[n]).if (a == 4) { break loop1. // Displays 'hello' break block1. // mygcd is a reference to the same function as gcd. a named argument in the definition that does not have a matching argument in the call will have the value undefined (which can be implicitly cast to false). // Number 3 is skiped } if (b == 6) { continue loop1. 'finished' is not shown } alert('b = ' + b). arguments[0]. // Parse error. A function may utilize local variables. including those beyond the number of named arguments. [edit] Functions A function is a block with a (possibly empty) parameter list that is normally given a name.g. diff) : gcd(segmentA. 40)).. If you exit the function without a return statement. alert(mygcd(60. alert('world'). the value undefined is returned. . // Stops after the 4th attempt } alert('a = ' + a). arguments[1]. // Will never get here } goto block1. (While the . ++b) { if (b == 3) { continue loop2. if (diff == 0) return segmentA. Note no argument ()s..

// ignores actual parameter p.length property. bar(). // writes 1 3 3 is additional Functions can be declared inside other functions. var obj2 = {b : 2}. and are often implemented using these data structures.b). which ordinary associative arrays do not have. bar = function() { alert(v) }. // 9 All parameters are passed by value (for objects it is the reference to the object that is passed).) function add7(x. baz = function(x) { v = x. . Objects may be thought of as associative arrays or hashes.arguments list has a . } foo(obj1. function foo(p) { p = obj2. } alert(x + y + arguments. it is not an instance of Array. 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). it does not have methods such as . alert(v). parameter alert(obj1. 4). var bar.a + " " + obj2. }. However. baz. . // 11 add7(3.sort(). // Does not affect obj1 at all. // Fugly (not fud) even though foo() has exited. 3). var v = "Top". } foo(). Furthermore they implement full closures by remembering the outer function's local variables even after the outer function has exited.slice(). Types are normally subdivided into primitives and objects. y) { if (!y) { y = 7. // Top [edit] Objects For convenience. and access the outer function's local variables.length). such as a prototype chain. objects have additional features. var obj1 = {a : 1}. function foo() { var v = "fud". etc.b = arguments[1]. baz("Fugly"). }. add7(3).

Rather. in a browser. RegExp and String. hobbies: ["chess".). form. Number. "jogging"] }. Function. age: 33. typical host objects belong to the DOM (window. namely Array. Math. // A != A2.JavaScript has several kinds of built-in objects. which is a simple notation that uses JavaScript-like syntax for data exchange. // Object literal var objectA = {}.". For example. a function can be called as a method. there is no distinction between a function definition and a method definition. [edit] Methods A method is simply a function that is assigned to the value of an object's slot. index2: 'value 2'}. Boolean. var objectB = {index1: 'value 1'. Object. last: "Smith" }. It is a convention that constructor functions are given a name that starts with a capital letter: // Constructor var anObject = new Object(). Unlike many object-oriented languages. the distinction occurs during function calling. (There are also call and apply methods that can set this explicitly—some packages such as jQuery do unusual things with this. Other objects are "host objects". // Custom constructor (see below) Object literals and array literals allow one to easily create flexible data structures: var myStructure = { name: { first: "Mel". {}s create new objects as copies. The constructor can use either a built-in Object function or a custom function. This is the basis for JSON. the standard local variable this is just automatically set to the object instance to the left of the ". links etc. Date. var objectA2 = {}.) . When called as a method. [edit] Creating objects Objects can be created using a constructor or an object literal. defined not by the language but by the runtime environment.

attributeB) { this.m4()).} function Foo(yz) { this. Note that in the example below.m3() + baz.pyz = function() {return this. // blue .pyz()). // foo1/2 a-Y b-Z foo1. } var foo1 = new Foo(1). } else { this.prefix + "Y".m3 = px. } MyObject. because foo1. some of which are functions.prefix + "X".}. // Assigns the function itself. this. not px() var baz = {"prefix": "c-"}. Foo is simply assigning values to slots. baz.pyz() + foo2.prefix = "a-".attributeB = attributeB.attributeA = attributeA. foo2.staticC).pyz = function() {return this.prefix = "b-".prefix + "Z". [edit] Constructors Constructor functions simply assign values to slots of a newly created object. The values may be data or other functions. There is no prototyping in this example. Example: Manipulating an object function MyObject(attributeA.m2 doesn't exist. // No need for a constructor to make an object.m1() + foo1. alert("foo1/2 " + foo1. not obj alert(MyObject. i. Foo is being used as a constructor. var foo2 = new Foo(0). There is nothing special about a constructor.staticC = "blue". alert("m1/m3/m4 " + foo1. not its evaluated result.m4 = px. it is just a method that is invoked after the object is created. // m1/m3/m4 a-X a-X c-X foo1. function px() {return this. this is set to the newly created object.m1 = px. } this.In the example below. Thus it can assign different functions to different instances. // Throws an exception.m2(). // On MyObject Function. if (yz > 0) { this.e.}.

staticC). which can be used to produce an effect similar to "static properties" (using C++/Java terminology) as shown below. // remove the whole Object (rarely used) alert(obj. y. until it is changed back with the identical value Functions are objects themselves. // except x. // 1000 alert(obj. [edit] Inheritance JavaScript supports inheritance hierarchies through prototyping in the manner of Self. When d is created as a Derived. // undefined delete obj. // add a new property delete obj.obj = new MyObject('red'.attributeA). 1000). So function Foo(){} // use of 'new' sets prototype and constructor slots ( eg // Foo. z instanceof Foo // true.constructor // true x instanceof Foo // true y instanceof Foo // false z = new {constructor: Foo}. In the following example. the reference to the base instance of Base is copied to d.constructor().constructor == y. // throws an exception The constructor itself is stored in the special slot constructor.attributeC = new Date(). // Above is almost equivalent to y = {}. (The function object also has a special prototype property.attributeA).) Object deletion is rarely used as the scripting engine will garbage collect objects that are no longer being referenced. // changing Foo.prototype = {}. y.constructor(). // remove a property of obj alert(obj. // red alert(obj["attributeB"]). alert(obj. as discussed in the Inheritance section below.base.constructor = Foo.attributeB. // would set constructor to Object ) x = new Foo(). // undefined obj. the Derived class inherits from the Base class.attributeB). .prototype after 'new' has been called can change the // instanceof results.

// bar.anOverride = function() {alert("Derived::anOverride()").m()).}. } base = new Base().prototype = t. // Must be before new Derived() d = new Derived(). Base.aBaseFunction).aBaseFunction().m = m3.} function m2() {return "Two".aBaseFunction. // Copies Derived.prototype = base.aBaseFunction = function() {alert("Base::aBaseFunction()").}. which is reflected in the value of d. bar = new Base(). this. // true in Mozilla-based implementations but false in many other implementations The following shows clearly how references to prototypes are copied on instance creation.aBaseFunction = function() {alert("Base::aNEWBaseFunction()")} d. function Base() { this. .__proto__ == base).anOverride = function() {alert("Base::anOverride()"). but that changes to a prototype can affect all instances that refer to it.m = m2. // Derived::anOverride() d.}.} function m3() {return "Three".aBaseFunction.Derive does not contain a value for aBaseFunction. // true alert(d. } function Derived() { this. Some implementations allow the prototype to be accessed or set explicitly using the __proto__ slot as shown below.} function Base() {} Base. Derived.prototype. // Base::aNEWBaseFunction() alert(d. so it is retrieved from Base when aBaseFunction is accessed. base. foo = new Base(). This is made clear by changing the value of base.aBaseFunction == Derived. alert("bar.m Two function Top() {this. function m1() {return "One".prototype to d instance's hidden prototype slot.m " + bar.} t = new Top().anOverride().prototype.

the script's control flow immediately transfers to the statements in the catch block..m Three t. Otherwise the catch block is skipped.m()). // baz. The catch argument is required. catch . as an extension to the ECMAScript standard. Either the catch or the finally clause may be omitted.m()). // Does affect baz. The Catch block can throw(errorValue) if it does not want to handle a specific error. finally exception handling statement to handle run-time errors. [edit] Exception handling JavaScript includes a try ...m " + baz. // foo. } "InvalidIdException") { statement.m()). // baz. the statements within the try block execute. and it can be both powerful and confusing.m1 " + baz. This can be used to free resources.. alert("baz..m Two baz = new Base(). and any other derived classes. Its syntax is as follows: try { // Statements in which exceptions might be thrown } catch(errorValue) { // Statements that execute in the event of an exception } finally { // Statements that execute afterward either way } Initially.// No effect on foo. although memory is automatically garbage collected.m " + foo. The try ... catch . alert("baz. } . finally statement catches exceptions resulting from an error or a throw statement. If an exception is thrown. } "InvalidEmailException") { statement.m = m1. The Mozilla implementation allows for multiple catch statements. (e if e == (e if e == (e if e == (e) } "InvalidNameException") { statement.m1 One In practice many variations of these themes are used. } { statement. They follow a syntax similar to that used in Java: try { catch catch catch catch statement. In any case the statements in the finally block are always executed. with the exception available as the error argument. the *reference* to t is copied.. alert("foo.

// shows 9. onerror = function (errorValue. alert("val " + eval("x+2"))..) [edit] eval (expression) Evaluates expression string parameter.}. Variables local to functions can be referenced by the expression.. which can include assignment statements. return true. lineNr) {. .In a browser.. })(). url. (function foo() { var x=7. [edit] Native functions and methods (Not related to web browsers. the onerror event is more commonly used to trap exceptions.