JavaScript syntax
Encyclopedia
The syntax of JavaScript
is the set of rules that define a correctly structured JavaScript program.
The examples below make use of the
lacks an official standard text output function. However, given that JavaScript is mainly used for client-side scripting
within modern web browser
s, and that almost all web browsers provide the
summarized the ancestry of the syntax in the first paragraph of the JavaScript 1.1 specification as follows:
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.
s, tabs and newline
s 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.
return
a + b;
// Returns undefined. Treated as:
// return;
// a + b;
But:
a = b + c
(d + e).foo
// Treated as:
// a = b + c(d + e).foo;
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 */
s in standard JavaScript have no type
attached, and any value can be stored in any variable. Variables are declared with a
letters (or \uXXXX Unicode escape sequences) can be used in identifiers. 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
. 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. As a consequence, a variable never declared will be global if assigned. Declaring a variable (with the keyword
Note that JavaScript's strict mode forbids the assignment of an undeclared variable, which avoids global namespace pollution.
is assigned to all uninitialized variables, and is also returned when checking for object properties that do not exist. In a Boolean context, the undefined value is considered a false value.
Note: Undefined is considered a true primitive-type. As such, when performing checks that enforce type checking, the undefined value will not equal other false types.
var test; // variable declared but not defined, ...
// ... set to value of undefined
var testObj = {};
alert(test); // test variable exists but value not ...
// ... defined, displays undefined
alert(testObj.myProp); // testObj exists, property does not, ...
// ... displays undefined
alert(undefined null); // unenforced type during check, displays true
Note: There is no built-in language literal for undefined. Thus (x undefined) is not a foolproof way to check whether a variable is undefined, because in versions before ECMAScript 5, it is legal for someone to write var undefined = "I'm defined now";. A more robust approach is to compare using (typeof x 'undefined').
Functions like this won't work as expected:
function isUndefined(x) { var u; return x u; } // like this...
void 0; } // ... or that one
Here, calling
Null
Unlike undefined, null
is often set to indicate that something has been declared but has been defined to be empty. In a Boolean context, the value of null is considered a false value in JavaScript.
Note: Null is a true primitive-type within the JavaScript language, of which null (note case) is the single value. As such, when performing checks that enforce type checking, the null value will not equal other false types. Surprisingly, null is considered an object by typeof.
alert(null undefined); // unenforced type during check, displays true
alert(null undefined); // enforce type during check, displays false
alert(typeof null 'object'); // true
Number
Numbers are represented in binary as IEEE-754 Doubles, which provides an accuracy nearly 16 significant digits. Because they are floating point
numbers, they do not always exactly represent real numbers, including fractions.
This becomes an issue when comparing or formatting numbers. For example:
alert(0.2 + 0.1 0.3); // displays false
alert(0.94 - 0.01); // displays 0.9299999999999999
As a result, a routine such as the toFixed method should be used to round numbers whenever they are formatted for output.
Numbers may be specified in any of these notations:
345; // an "integer", although there is only one numeric type in JavaScript
34.5; // a floating-point number
3.45e2; // another floating-point, equivalent to 345
0377; // an octal integer equal to 255
0xFF; // a hexadecimal integer equal to 255, digits represented by the ...
// ... letters A-F may be upper or lowercase
The extents +∞, −∞
and NaN
(Not a Number) of the number type may be obtained by two program expressions:
Infinity; // Positive Infinity (negative obtained with -Infinity for instance)
NaN; // The Not-A-Number value, also returned as a failure in ...
// ... string-to-number conversions
These three special values correspond and behave as the IEEE-754 describes them.
The Number constructor, or a unary + or -, may be used to perform explicit numeric conversion:
var myString = "123.456";
var myNumber1 = Number(myString);
var myNumber2 = +myString;
When used as a constructor, a numeric wrapper object is created, (though it is of little use):
myNumericWrapper = new Number(123.456);
String
A string
in Javascript is a sequence of characters. In JavaScript strings can be created directly by placing the series of characters between double or single quotes.
var greeting = "Hello, world!";
var anotherGreeting = 'Greetings, people of Earth.';
You can access individual characters within a string using the charAt method (provided by
var h = greeting.charAt(0);
In Modern browsers, 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];
But JavaScript strings are immutable
:
greeting[0] = "H"; // Not Working
Applying the equality operator ("") to two strings returns true if the strings have the same contents, which means: of same length and same cases (for alphabets). Thus:
"Hello, world"); // Now compare1 contains true
var compare2 = ("Hello, " +x "hello, world"); // Now compare2 contains ...
// ... false since the ...
// ... first characters ...
// ... of both operands ...
// ... are not of the same case
You cannot use quotes of the same type inside the quotes unless they are escaped.
var x = '"Hello, world!" he said.' //Just fine.
var x = ""Hello, world!" he said." //Not good.
var x = "\"Hello, world!\" he said." //That works by replacing " with \"
It is possible to create a string using the String constructor:
var greeting = new String("Hello, world!");
These objects have a
var s = new String("Hello !");
typeof s; // Is 'object'
typeof s.valueOf; // Is 'string'
Equality between two String objects does not behave as with string primitives:
var s1 = new String("Hello !");
var s2 = new String("Hello !");
s1 s2; // Is false, because they are two distinct objects
s1.valueOf s2.valueOf; // Is true
Boolean
JavaScript
provides a Boolean data type with
evaluates as
When type conversion is required, JavaScript converts String, Number, Boolean, or Object operands as follows:
: The string is converted to a number value. JavaScript attempts to convert the string numeric literal to a Number type value. First, a mathematical value is derived from the string numeric literal. Next, this value is rounded to nearest Number type value.
: If one of the operands is a Boolean, the Boolean operand is converted to 1 if it is
: If an object is compared with a number or string, JavaScript attempts to return the default value for the object. An object is converted to a primitive String or Number value, using the
Some experts use the terms "truthy" and "falsy" to describe how values of various types behave when evaluated in a logical context, especially in regard to edge cases.
The binary logical operators returned a Boolean value in early versions of JavaScript, but now they return one of the operands instead. The left–operand is returned if it can be evaluated as:
, or
; otherwise the right–operand is returned. 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, or objects that can be evaluated as such a string) because the boolean operand will be compared as a numeric value. This may be unexpected. An expression can be explicitly cast to a boolean primitive by: doubling the logical negation operator (
, using the
The
Native objects
The JavaScript language provides a handful of native objects
. JavaScript native objects are considered part of the JavaScript specification. JavaScript environment notwithstanding, this set of objects should always be available.
is a JavaScript object prototyped from the Array constructor specifically designed to store data values indexed by integer keys. Arrays, unlike the basic Object type, are prototyped with methods and properties to aid the programmer in routine tasks (e.g.,
As in the C family, arrays use a zero-based indexing scheme: A value that is inserted into an empty array by means of the
var myArray = []; // Point the variable myArray to a newly ...
// ... created, empty Array
myArray.push("hello world"); // Fill the next empty index, in this case 0
alert(myArray[0]); // Equivalent to alert("hello world");
Arrays have a
Elements of Arrays may be accessed using normal object property access notation:
myArray[1]; // the 2nd item in myArray
myArray["1"];
The above 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
myArray = [0, 1, , , 4, 5]; // array with length 6 and 6 elements, ...
// ... including 2 undefined 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 array
s". Setting
One can use the object declaration literal to create objects that behave much like associative arrays in other languages:
dog = {color: "brown", size: "large"};
dog["color"]; // results in "brown"
dog.color; // also results in "brown"
One can use the object and array declaration literals to quickly create arrays that are associative, multidimensional, or both.
(Technically, JavaScript does not support multidimensional arrays, but one can mimic them with arrays-of-arrays.)
cats = [{color: "brown", size: "large"},
{color: "black", size: "small"}];
cats[0]["size"]; // results in "large"
dogs = {rover: {color: "brown", size: "large"},
spot: {color: "black", size: "small"}};
dogs["spot"]["size"]; // results in "small"
dogs.rover.color; // results in "brown"
new Date // create a new Date instance representing the current time/date.
new Date(2010, 2, 1) // create a new Date instance representing 2010-Mar-01 00:00:00
new Date(2010, 2, 1, 14, 25, 30) // create a new Date instance representing 2010-Mar-01 14:25:30
new Date("2010-3-1 14:25:30") // create a new Date instance from a String.
Methods to extract fields are provided, as well as a useful
var d = new Date(2010, 2, 1, 14, 25, 30); // 2010-Mar-01 14:25:30
// Displays '2010-3-1 14:25:30':
alert(d.getFullYear + '-' + (d.getMonth+1) + '-' + d.getDate + ' '
+ d.getHours + ':' + d.getMinutes + ':' + d.getSeconds);
// Built-in toString returns something like 'Mon Mar 01 2010 14:25:30 GMT-0500 (EST)':
alert(d);
throw new Error("Something went wrong.");
Nested within conditional statements, such instantiations can substitute for try/catch blocks:
var emailAddress = prompt("Please enter your e-mail address:", "");
if (!emailAddress || emailAddress.length 0) {
throw new Error("Excuse me: You must enter your e-mail address to continue.");
}
s, not degrees
or grads
.
/expression/.test(string);
"string".search(/expression/);
"string".replace(/expression/,replacement);
// Here are some examples
if(/Tom/.test("My name is Tom")) alert("Hello Tom!");
alert("My name is Tom".search(/Tom/)); // 11 (letters before Tom)
"My name is John"
Character Classes:
// \d - digit
// \D - non digit
// \s - space
// \S - non space
// \w - word char
// \W - non word
// [ ] - one of
// [^ ] - one not of
// - - range
if (/\d/.test('0')) alert('Digit');
if (/[0-9]/.test('5')) alert('Digit');
if (/[13579]/.test('1')) alert('Odd number');
if (/\S\S\s\S\S\S\S/.test('My name')) alert('Format OK');
if (/\w\w\w/.test('Tom')) alert('Format OK');
if (/[a-z]/.test('b')) alert('Small letter');
if (/[A-Z]/.test('B')) alert('Big letter');
if (/[a-zA-Z]/.test('B')) alert('Letter');
Character matching:
// A...Z a...z 0...9 - alphanumeric
// \u0000...\uFFFF - Unicode hexadecimal
// \x00...\xFF - ASCII hexadecimal
// \t - tab
// \n - new line
// \r - CR
// . - any character
// | - OR
if (/T.m/.test('Tom')) alert ('Hi Tom, Tam or Tim');
if (/A|B/.test("A")) alert ('A or B');
Repeaters:
// ? - 0 or 1 match
// * - 0 or more
// + - 1 or more
// {n} - exactly n
// {n,} - n or more
// {0,n} - n or less
// {n,m} - range n to m
if (/ab?c/.test("ac")) alert("OK"); // match: "ac", "abc"
if (/ab*c/.test("ac")) alert("OK"); // match: "ac", "abc", "abbc", "abbbc" etc.
if (/ab+c/.test("abc")) alert("OK"); // match: "abc", "abbc", "abbbc" etc.
if (/ab{3}c/.test("abbbc")) alert("OK"); // match: "abbbc"
if (/ab{3,}c/.test("abbbc")) alert("OK"); // match: "abbbc", "abbbbc", "abbbbbc" etc.
if (/ab{1,3}c/.test("abc")) alert("OK"); // match: "abc","abbc", "abbbc"
Anchors:
// ^ - string starts with
// $ - string ends with
if (/^My/.test("My name is Tom")) alert ("Hi!");
if (/Tom$/.test("My name is Tom")) alert ("Hi Tom!");
Subexpression
// - groups characters
if (/water(mark)?/.test("watermark")) alert("Here is water!"); // match: "water", "watermark",
if (/(Tom)|(John)/.test("John")) alert("Hi Tom or John!");
Flags:
// /g - global
// /i - ignore upper/lower case
// /m - allow matches to span multiple lines
alert("hi tom!".replace(/Tom/i,"John")); // "hi John!"
"ratutam"
alert("ratatam".replace(/ta/g,"tu")); // "ratutum"
Advanced methods
my_array = my_string.split(my_delimiter);
// example
my_array = "dog,cat,cow".split(","); // my_array("dog","cat","cow");
my_array = my_string.match(my_expression);
// example
my_array = "We start at 11:30, 12:15 and 16:45".match(/\d\d:\d\d/); // my_array=("11:30","12:15","16:45");
Capturing groups
var myRe = /(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})/;
var results = myRe.exec("The date and time are 2009-09-08 09:37:08.");
if (results) {
alert("Matched: " + results[0]); // Entire match
var my_date = results[1]; // First group "2009-09-08"
"09:37:08"
alert("It is " + my_time + " on " + my_date);
} else alert("Did not find a valid date!");
//x,y is the argument. 'return x+y' is the function body, which is the last in the argument list.
var add = new Function('x', 'y', 'return x+y');
var t = add(1, 2);
alert(t); //3
The add function above is often defined using the following pattern, as this pattern is faster and more intuitive.
function add(x, y) {
return x + y;
}
var t = add(1, 2);
alert(t); //3
A function instance has properties and methods.
function subtract(x, y) {
return x - y;
}
alert(subtract.length);//2,expected amount of arguments.
alert(subtract.toString);
/*
function subtract(x, y) {
return x - y;
}
: it is used for string concatenation and arithmetic addition. This may cause problems when inadvertently mixing strings and numbers. As a unary operator, it can convert a numeric string to a number.
// Concatenate 2 strings
alert('He' + 'llo'); // displays Hello
// Add two numbers
alert(2 + 6); // displays 8
// Adding a number and a string results in concatenation
alert(2 + '2'); // displays 22
alert('$' + 3 + 4); // displays $34, but $7 may have been expected
alert('$' + (3 + 4)); // displays $7
// Convert a string to a number
alert(+'2' 2); // displays true
Arithmetic
JavaScript supports the following binary arithmetic operators:
/ Division (returns a floating-point value)
% Modulus (returns the integer remainder)
JavaScript supports the following unary arithmetic operators:
var x = 1;
alert(++x); // displays: 2
alert(x++); // displays: 2; x becomes 3 then
alert(x); // displays: 3
alert(x--); // displays: 3; x becomes 2 then
alert(x); // displays: 2
alert(--x); // displays: 1
Assign
+= Add and assign
-= Subtract and assign
/= Divide and assign
%= Modulus and assign
Assignment of primitive types
var x = 1;
x *= 3;
alert(x); // displays: 3
x /= 3;
alert(x); // displays: 1
x -= 1;
alert(x); // displays: 0
Assignment of object types
var obj_1 = {a: 1};
var obj_2 = {a: 0};
var obj_3 = obj_2;// obj_3 is a reference to obj_2
obj_2.a = 2;
alert(obj_1.a + " " + obj_2.a + " " + obj_3.a); // displays 1 2 2
obj_2 = obj_1;// obj_2 now references obj_1
// obj_3 now the only reference to what was obj_2
alert(obj_1.a + " " + obj_2.a + " " + obj_3.a); // displays 1 1 2
obj_2.a = 7;// modifies obj_1
alert(obj_1.a + " " + obj_2.a + " " + obj_3.a); // displays 7 7 2
var a, b, c, d, e;
[a, b] = [3, 4];
alert(a + ',' + b); // displays: 3,4
e = {foo: 5, bar: 6, baz: ['Baz', 'Content']};
var arr = [];
({baz: [arr[0], arr[3]], foo: a, bar: b}) = e;
alert(a + ',' + b + ',' + arr); // displays: 5,6,Baz,,,Content
[a, b] = [b, a]; // swap contents of a and b
alert(a + ',' + b); // displays: 6,5
Equal
Not identical
When comparing variables which are objects they are considered to be different if their objects are not the same object, even if the values of them are the same, so:
See also String.
In the context of a logical operation, any expression evaluates to true except the following:
The Boolean function can be used to explicitly convert to a primitive of type Boolean:
// Only empty strings return false
alert(Boolean("") false);
true);
alert(Boolean("0") true);
false);
alert(Boolean(0) false);
false); // equivalent to -1*0
alert(Boolean(-2) true );
true);
alert(Boolean({}) true);
true);
// These types return false
alert(Boolean(null) false);
false); // equivalent to Boolean
The NOT operator evaluates its operand as a Boolean, and returns the negation. Using the operator twice in a row, as a double negative
, explicitly converts an expression to a primitive of type Boolean:
alert( !0 Boolean(1));
Boolean(0)); alert(Boolean(0)
alert(!"" Boolean("s"));
Boolean("")); alert(Boolean("")
The ternary operator can also be used for explicit conversion:
alert([] false); alert([] ? true : false); // “truthy” but the comparison uses [].toString
false); alert([0]? true : false); // [0].toString "0"
false); alert("0"? true : false); // "0" → 0 … (00) … 0 ← false
true); alert([1]? true : false); // [1].toString "1"
true); alert("1"? true : false); // "1" → 1 … (11) … 1 ← true
"2"
alert("2" != true); alert("2"? true : false); // "2" → 2 … (2!=1) … 1 ← true
Expressions that use features such as post–incrementation, (
. JavaScript provides short-circuit evaluation of expressions; the right operand is only executed if the left operand does not suffice to determine the value of the expression.
alert(a || b); // When a is true, there is no reason to evaluate b.
alert(a && b); // When a is false, there is no reason to evaluate b.
alert(c ? t : f); // When c is true, there is no reason to evaluate f.
In early versions of JavaScript and JScript, the binary logical operators returned a Boolean value (like most C–derived programming languages). However, all contemporary implementations return one of their operands instead:
alert(a || b); // if a is true, return a, otherwise return b
alert(a && b); // if a is false, 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)"; // assigns t, or the default value if t is null, empty, etc.
JavaScript supports the following unary bitwise operators:
Assignment
+ Concatenation
+= Concatenate and assign
Examples
str = "ab" + "cd"; // "abcd"
str += "e"; // "abcde"
str2 = "2"+2 // "22", not "4" or 4.
if (expr) {
//statements;
} else if (expr2) {
//statements;
} else {
//statements;
}
result = condition ? expression : alternative;
is the same as:
if (condition) {
result = expression;
} else {
result = alternative;
}
Unlike the if statement, the conditional operator cannot omit its "else-branch".
switch (expr) {
case SOMEVALUE:
//statements;
break;
case ANOTHERVALUE:
//statements;
break;
default:
//statements;
break;
}
is as follows:
for (initial; condition; loop statement) {
/*
statements will be executed every time
the for{} loop cycles, while the
condition is satisfied
*/
}
or
for (initial; condition; loop statement) // one statement
is as follows:
for (var property_name in some_object) {
//statements using some_object[property_name];
}
is as follows:
while (condition) {
statement1;
statement2;
statement3;
...
}
is as follows:
do {
statement1;
statement2;
statement3;
...
} while (condition);
with (document) {
var a = getElementById('a');
var b = getElementById('b');
var c = getElementById('c');
};
The semantics are similar to the
.
is a reserved word, it does not work in JavaScript.
loop1: for (var a = 0; a < 10; a++) {
if (a 4) {
3) {
continue loop2; // Number 3 is skiped
}
if (b 6) {
continue loop1; // Continues the first loop, 'finished' is not shown
}
alert('b = ' + b);
}
alert('finished')
}
block1: {
alert('hello'); // Displays 'hello'
break block1;
alert('world'); // Will never get here
}
goto block1; // Parse error.
Functions
A function is a block with a (possibly empty) parameter list that is normally given a name. A function may utilize local variables. If you exit the function without a return statement, the value
function gcd(segmentA, segmentB) {
var diff = segmentA - segmentB;
if (diff 0)
return segmentA;
return diff > 0 ? gcd(segmentB, diff) : gcd(segmentA, -diff);
}
alert(gcd(60, 40)); // 20
var mygcd=gcd; // mygcd is a reference to the same function as gcd. Note no argument s.
alert(mygcd(60, 40)); // 20
Functions are first class objects and may be assigned to other variables.
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
function add7(x, y) {
if (!y) {
y = 7;
}
alert(x + y + arguments.length);
};
add7(3); // 11
add7(3, 4); // 9
All parameters are passed by value (for objects it is the reference to the object that is passed).
var obj1 = {a : 1};
var obj2 = {b : 2};
function foo(p) {
p = obj2; // ignores actual parameter
p.b = arguments[1];
}
foo(obj1, 3); // Does not affect obj1 at all. 3 is additional parameter
alert(obj1.a + " " + obj2.b); // writes 1 3
Functions can be declared inside other functions, and access the outer function's local variables. Furthermore they implement full closure
s by remembering the outer function's local variables even after the outer function has exited.
var v = "Top";
var bar, baz;
function foo {
var v = "fud";
bar = function { alert(v) };
baz = function(x) { v = x; };
}
foo;
baz("Fugly");
bar; // Fugly (not fud) even though foo has exited.
alert(v); // Top
terminology). Objects may be thought of as associative arrays or hashes, and are often implemented using these data structures. However, objects have additional features, such as a prototype chain, which ordinary associative arrays do not have.
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.).
// Constructor
var anObject = new Object;
// Object literal
var objectA = {};
var objectA2 = {}; // A != A2, {}s create new objects as copies.
var objectB = {index1: 'value 1', index2: 'value 2'};
// Custom constructor (see below)
Object literals and array literals allow one to easily create flexible data structures:
var myStructure = {
name: {
first: "Mel",
last: "Smith"
},
age: 33,
hobbies: ["chess", "jogging"]
};
This is the basis for JSON
, which is a simple notation that uses JavaScript-like syntax for data exchange.
is simply a function that is assigned to the value of an object's slot. Unlike many object-oriented languages, there is no distinction between a function definition and a method definition. Rather, the distinction occurs during function calling; a function can be called as a method.
When called as a method, the standard local variable this is just automatically set to the object instance to the left of the ".". (There are also call and apply methods that can set this explicitly—some packages such as jQuery
do unusual things with this.)
In the example below, Foo is being used as a constructor. There is nothing special about a constructor, it is just a method that is invoked after the object is created. this is set to the newly created object.
Note that in the example below, Foo is simply assigning values to slots, some of which are functions. Thus it can assign different functions to different instances. There is no prototyping in this example.
function px {return this.prefix + "X";}
function Foo(yz) {
this.prefix = "a-";
if (yz > 0) {
this.pyz = function {return this.prefix + "Y";};
} else {
this.pyz = function {return this.prefix + "Z";};
}
this.m1 = px;
}
var foo1 = new Foo(1);
var foo2 = new Foo(0);
foo2.prefix = "b-";
alert("foo1/2 " + foo1.pyz + foo2.pyz);
// foo1/2 a-Y b-Z
foo1.m3 = px; // Assigns the function itself, not its evaluated result, i.e. not px
var baz = {"prefix": "c-"};
baz.m4 = px; // No need for a constructor to make an object.
alert("m1/m3/m4 " + foo1.m1 + foo1.m3 + baz.m4);
// m1/m3/m4 a-X a-X c-X
foo1.m2; // Throws an exception, because foo1.m2 doesn't exist.
Example: Manipulating an object
function MyObject(attributeA, attributeB) {
this.attributeA = attributeA;
this.attributeB = attributeB;
}
MyObject.staticC = "blue"; // On MyObject Function, not obj
alert(MyObject.staticC); // blue
obj = new MyObject('red', 1000);
alert(obj.attributeA); // red
alert(obj["attributeB"]); // 1000
alert(obj.staticC); // undefined
obj.attributeC = new Date; // add a new property
delete obj.attributeB; // remove a property of obj
alert(obj.attributeB); // undefined
delete obj; // remove the whole Object (rarely used)
alert(obj.attributeA); // throws an exception
The constructor itself is stored in the special slot constructor. So
function Foo{}
// use of 'new' sets prototype and constructor slots ( eg
// Foo.prototype = {}; // would set constructor to Object )
x = new Foo;
// Above is almost equivalent to
y = {};
y.constructor = Foo;
y.constructor;
// except
x.constructor y.constructor // true
x instanceof Foo // true
y instanceof Foo // false
z = new {constructor: Foo}.constructor;
z instanceof Foo // true.
// changing Foo.prototype after 'new' has been called can change the
// instanceof results, until it is changed back with the identical value
Functions are objects themselves, which can be used to produce an effect similar to "static properties" (using C++/Java terminology) as shown below. (The function object also has a special
Object deletion is rarely used as the scripting engine will garbage collect
objects that are no longer being referenced.
In the following example, the Derived class inherits from the Base class.
When d is created as a Derived, the reference to the base instance of Base is copied to d.base.
Derive does not contain a value for aBaseFunction, so it is retrieved from Base when aBaseFunction is accessed.
This is made clear by changing the value of base.aBaseFunction, which is reflected in the value of d.aBaseFunction.
Some implementations allow the prototype to be accessed or set explicitly using the __proto__ slot as shown below.
function Base {
this.anOverride = function {alert("Base::anOverride");};
this.aBaseFunction = function {alert("Base::aBaseFunction");};
}
function Derived {
this.anOverride = function {alert("Derived::anOverride");};
}
base = new Base;
Derived.prototype = base; // Must be before new Derived
d = new Derived; // Copies Derived.prototype to d instance's hidden prototype slot.
base.aBaseFunction = function {alert("Base::aNEWBaseFunction")}
d.anOverride; // Derived::anOverride
d.aBaseFunction; // Base::aNEWBaseFunction
alert(d.aBaseFunction Derived.prototype.aBaseFunction); // true
alert(d.__proto__ base); // true in Mozilla-based implementations but false in many other implementations
The following shows clearly how references to prototypes are copied on instance creation, but that changes to a prototype can affect all instances that refer to it.
function m1 {return "One";}
function m2 {return "Two";}
function m3 {return "Three";}
function Base {}
Base.prototype.m = m2;
bar = new Base;
alert("bar.m " + bar.m); // bar.m Two
function Top {this.m = m3;}
t = new Top;
foo = new Base;
Base.prototype = t;
// No effect on foo, the *reference* to t is copied.
alert("foo.m " + foo.m); // foo.m Two
baz = new Base;
alert("baz.m " + baz.m); // baz.m Three
t.m = m1; // Does affect baz, and any other derived classes.
alert("baz.m1 " + baz.m); // baz.m1 One
In practice many variations of these themes are used, and it can be both powerful and confusing.
Exception handling
JavaScript includes a
statement to handle run-time errors.
The
resulting from an error or a throw statement. 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, 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. The Catch block can
In any case the statements in the finally block are always executed. This can be used to free resources, although memory is automatically garbage collected.
Either the
The Mozilla implementation allows for multiple catch statements, as an extension to the ECMAScript standard. They follow a syntax similar to that used in Java
:
try { statement; }
catch (e if e "InvalidNameException") { statement; }
catch (e if e "InvalidIdException") { statement; }
"InvalidEmailException") { statement; }
catch (e) { statement; }
In a browser, the
onerror = function (errorValue, url, lineNr) {...; return true;};
(function foo {
var x=7;
alert("val " + eval("x+2"));
}); // shows 9.
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....
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 libraryStandard library
A standard library for a programming language is the library that is conventionally made available in every implementation of that language. In some cases, the library is described directly in the programming language specification; in other cases, the contents of the standard library are...
lacks an official standard text output function. However, given that JavaScript is mainly used for client-side scripting
Client-side scripting
Client-side scripting generally refers to the class of computer programs on the web that are executed client-side, by the user's web browser, instead of server-side...
within modern web browser
Web browser
A web browser is a software application for retrieving, presenting, and traversing information resources on the World Wide Web. An information resource is identified by a Uniform Resource Identifier and may be a web page, image, video, or other piece of content...
s, and that almost all web browsers provide the
alert
function, alert
is used in the examples.Origins
Brendan EichBrendan Eich
Brendan Eich is a computer programmer and creator of the JavaScript scripting language. He is the chief technology officer at the Mozilla Corporation.-Education:...
summarized the ancestry of the syntax in the first paragraph of the JavaScript 1.1 specification as follows:
Case sensitivity
JavaScript is case sensitive.It is common to start the name of a constructor
Constructor (computer science)
In object-oriented programming, a constructor in a class is a special type of subroutine called at the creation of an object. It prepares the new object for use, often accepting parameters which the constructor uses to set any member variables required when the object is first created...
with a capitalised
CamelCase
CamelCase , also known as medial capitals, is the practice of writing compound words or phrases in which the elements are joined without spaces, with each element's initial letter capitalized within the compound and the first letter either upper or lower case—as in "LaBelle", "BackColor",...
letter, and the name of a function or variable with a lower-case letter.
Whitespace and semicolons
SpaceSpace (punctuation)
In writing, a space is a blank area devoid of content, serving to separate words, letters, numbers, and punctuation. Conventions for interword and intersentence spaces vary among languages, and in some cases the spacing rules are quite complex....
s, tabs and newline
Newline
In computing, a newline, also known as a line break or end-of-line marker, is a special character or sequence of characters signifying the end of a line of text. The name comes from the fact that the next character after the newline will appear on a new line—that is, on the next line below the...
s used outside of string constants are called whitespace
Whitespace (computer science)
In computer science, whitespace is any single character or series of characters that represents horizontal or vertical space in typography. When rendered, a whitespace character does not correspond to a visual mark, but typically does occupy an area on a page...
. 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.
return
a + b;
// Returns undefined. Treated as:
// return;
// a + b;
But:
a = b + c
(d + e).foo
// Treated as:
// a = b + c(d + e).foo;
Comments
CommentComment (computer programming)
In computer programming, a comment is a programming language construct used to embed programmer-readable annotations in the source code of a computer program. Those annotations are potentially significant to programmers but typically ignorable to compilers and interpreters. Comments are usually...
syntax is the same as in C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...
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 */
Variables
VariableVariable (programming)
In computer programming, a variable is a symbolic name given to some known or unknown quantity or information, for the purpose of allowing the name to be used independently of the information it represents...
s in standard JavaScript have no type
Type system
A type system associates a type with each computed value. By examining the flow of these values, a type system attempts to ensure or prove that no type errors can occur...
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 UnicodeUnicode
Unicode is a computing industry standard for the consistent encoding, representation and handling of text expressed in most of the world's writing systems...
letters (or \uXXXX Unicode escape sequences) can be used in identifiers. 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 globalGlobal variable
In computer programming, a global variable is a variable that is accessible in every scope . Interaction mechanisms with global variables are called global environment mechanisms...
. 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. 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.
Primitive data types
The JavaScript language provides a handful of primitive data types. Some of the primitive data types also provide a set of named values that represent the extents of the type boundaries. These named values are described within the appropriate sections below.Undefined
The value of "undefined"Undefined value
In computing , undefined value is a condition where an expression has not a correct value, although it is syntactically correct. Undefined value may not be confused with empty string, boolean "false" or other "empty" values...
is assigned to all uninitialized variables, and is also returned when checking for object properties that do not exist. In a Boolean context, the undefined value is considered a false value.
Note: Undefined is considered a true primitive-type. As such, when performing checks that enforce type checking, the undefined value will not equal other false types.
var test; // variable declared but not defined, ...
// ... set to value of undefined
var testObj = {};
alert(test); // test variable exists but value not ...
// ... defined, displays undefined
alert(testObj.myProp); // testObj exists, property does not, ...
// ... displays undefined
alert(undefined
null); // unenforced type during check, displays true
alert(undefined null); // enforce type during check, displays false
Note: There is no built-in language literal for undefined. Thus (x undefined) is not a foolproof way to check whether a variable is undefined, because in versions before ECMAScript 5, it is legal for someone to write var undefined = "I'm defined now";. A more robust approach is to compare using (typeof x 'undefined').
Functions like this won't work as expected:
function isUndefined(x) { var u; return x
u; } // like this...
function isUndefined(x) { return x
void 0; } // ... or that oneHere, calling
isUndefined(my_var)
raises a ReferenceError if my_var
is an unknown identifier, whereas typeof my_var 'undefined'
doesn't.Null
Unlike undefined, null
Null Object pattern
In object-oriented computer programming, a Null Object is an object with defined neutral behavior. The Null Object design pattern describes the uses of such objects and their behavior . It was first published in the Pattern Languages of Program Design book series.-Motivation:In most...
is often set to indicate that something has been declared but has been defined to be empty. In a Boolean context, the value of null is considered a false value in JavaScript.
Note: Null is a true primitive-type within the JavaScript language, of which null (note case) is the single value. As such, when performing checks that enforce type checking, the null value will not equal other false types. Surprisingly, null is considered an object by typeof.
alert(null undefined); // unenforced type during check, displays true
alert(null undefined); // enforce type during check, displays false
alert(typeof null
'object'); // true
Number
Numbers are represented in binary as IEEE-754 Doubles, which provides an accuracy nearly 16 significant digits. Because they are floating point
Floating point
In computing, floating point describes a method of representing real numbers in a way that can support a wide range of values. Numbers are, in general, represented approximately to a fixed number of significant digits and scaled using an exponent. The base for the scaling is normally 2, 10 or 16...
numbers, they do not always exactly represent real numbers, including fractions.
This becomes an issue when comparing or formatting numbers. For example:
alert(0.2 + 0.1 0.3); // displays false
alert(0.94 - 0.01); // displays 0.9299999999999999
As a result, a routine such as the toFixed method should be used to round numbers whenever they are formatted for output.
Numbers may be specified in any of these notations:
345; // an "integer", although there is only one numeric type in JavaScript
34.5; // a floating-point number
3.45e2; // another floating-point, equivalent to 345
0377; // an octal integer equal to 255
0xFF; // a hexadecimal integer equal to 255, digits represented by the ...
// ... letters A-F may be upper or lowercase
The extents +∞, −∞
Extended real number line
In mathematics, the affinely extended real number system is obtained from the real number system R by adding two elements: +∞ and −∞ . The projective extended real number system adds a single object, ∞ and makes no distinction between "positive" or "negative" infinity...
and NaN
NaN
In computing, NaN is a value of the numeric data type representing an undefined or unrepresentable value, especially in floating-point calculations...
(Not a Number) of the number type may be obtained by two program expressions:
Infinity; // Positive Infinity (negative obtained with -Infinity for instance)
NaN; // The Not-A-Number value, also returned as a failure in ...
// ... string-to-number conversions
These three special values correspond and behave as the IEEE-754 describes them.
The Number constructor, or a unary + or -, may be used to perform explicit numeric conversion:
var myString = "123.456";
var myNumber1 = Number(myString);
var myNumber2 = +myString;
When used as a constructor, a numeric wrapper object is created, (though it is of little use):
myNumericWrapper = new Number(123.456);
String
A string
String (computer science)
In formal languages, which are used in mathematical logic and theoretical computer science, a string is a finite sequence of symbols that are chosen from a set or alphabet....
in Javascript is a sequence of characters. In JavaScript strings can be created directly by placing the series of characters between double or single quotes.
var greeting = "Hello, world!";
var anotherGreeting = 'Greetings, people of Earth.';
You can access individual characters within a string using the charAt method (provided by
String.prototype
). This is the preferred way when accessing individual characters within a string, as it also works in nonmodern browsers:var h = greeting.charAt(0);
In Modern browsers, 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];
But JavaScript strings are immutable
Immutable object
In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created...
:
greeting[0] = "H"; // Not Working
Applying the equality operator ("
") to two strings returns true if the strings have the same contents, which means: of same length and same cases (for alphabets). Thus:
var x = "world";
var compare1 = ("Hello, " +x
"Hello, world"); // Now compare1 contains truevar x = "world";
var compare1 = ("Hello, " +x
var compare2 = ("Hello, " +x "hello, world"); // Now compare2 contains ...
// ... false since the ...
// ... first characters ...
// ... of both operands ...
// ... are not of the same case
You cannot use quotes of the same type inside the quotes unless they are escaped.
var x = '"Hello, world!" he said.' //Just fine.
var x = ""Hello, world!" he said." //Not good.
var x = "\"Hello, world!\" he said." //That works by replacing " with \"
It is possible to create a string using the String constructor:
var greeting = new String("Hello, world!");
These objects have a
valueOf
method returning the primitive string wrapped into them:var s = new String("Hello !");
typeof s; // Is 'object'
typeof s.valueOf; // Is 'string'
Equality between two String objects does not behave as with string primitives:
var s1 = new String("Hello !");
var s2 = new String("Hello !");
s1 s2; // Is false, because they are two distinct objects
s1.valueOf s2.valueOf; // Is true
Boolean
JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....
provides a Boolean data type with
true
and false
literals. The typeof
operator returns the string "boolean"
for these primitive types. When used in a logical context, 0
, -0
, null
, NaN
, undefined
, and the empty string (""
) evaluate as false
due to automatic type coercion. The complementComplement
In many different fields, the complement of X is something that together with X makes a complete whole—something that supplies what X lacks.Complement may refer to:...
evaluates as
true
, including the strings "0"
, "false"
and any object (except null
). Automatic type coercion by the equality comparison operators (
and !=
) can be avoided by using the type checked comparison operators, (
and !
).When type conversion is required, JavaScript converts String, Number, Boolean, or Object operands as follows:
: The string is converted to a number value. JavaScript attempts to convert the string numeric literal to a Number type value. First, a mathematical value is derived from the string numeric literal. Next, this value is rounded to nearest Number type value.
: If one of the operands is a Boolean, the Boolean operand is converted to 1 if it is
true
or to 0 if it is false
.: If an object is compared with a number or string, JavaScript attempts to return the default value for the object. An object is converted to a primitive String or Number value, using the
.valueOf
or .toString
methods of the object. If this fails, a runtime error is generated.Some experts use the terms "truthy" and "falsy" to describe how values of various types behave when evaluated in a logical context, especially in regard to edge cases.
The binary logical operators returned a Boolean value in early versions of JavaScript, but now they return one of the operands instead. The left–operand is returned if it can be evaluated as:
false
, in the case of conjunction (a && b
)Logical conjunction
In logic and mathematics, a two-place logical operator and, also known as logical conjunction, results in true if both of its operands are true, otherwise the value of false....
, or
true
, in the case of disjunction (a
Logical disjunction
In logic and mathematics, a two-place logical connective or, is a logical disjunction, also known as inclusive disjunction or alternation, that results in true whenever one or more of its operands are true. E.g. in this context, "A or B" is true if A is true, or if B is true, or if both A and B are...
; otherwise the right–operand is returned. 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, or objects that can be evaluated as such a string) because the boolean operand will be compared as a numeric value. This may be unexpected. An expression can be explicitly cast to a boolean primitive by: doubling the logical negation operator (
!!
)Negation
In logic and mathematics, negation, also called logical complement, is an operation on propositions, truth values, or semantic values more generally. Intuitively, the negation of a proposition is true when that proposition is false, and vice versa. In classical logic negation is normally identified...
, using the
Boolean
function, or using the conditional operator (c ? t : f
).The
new
operator can be used to create an object wrapper for a Boolean primitive. However, the typeof
operator does not return "boolean"
for the object wrapper, it returns "object"
. Because all objects evaluate as true
, a method such as .valueOf
, or .toString
, must be used to retrieve the wrapped value. For explicit coercion to the Boolean type, Mozilla recommends that the Boolean
function (without new
) be used in preference to the Boolean object.Native objects
The JavaScript language provides a handful of native objects
Object (computer science)
In computer science, an object is any entity that can be manipulated by the commands of a programming language, such as a value, variable, function, or data structure...
. JavaScript native objects are considered part of the JavaScript specification. JavaScript environment notwithstanding, this set of objects should always be available.
Array
An ArrayArray data type
In computer science, an array type is a data type that is meant to describe a collection of elements , each selected by one or more indices that can be computed at run time by the program. Such a collection is usually called an array variable, array value, or simply array...
is a JavaScript object prototyped from the Array constructor specifically designed to store data values indexed by integer keys. Arrays, unlike the basic Object type, are prototyped with methods and properties to aid the programmer in routine tasks (e.g.,
join
, slice
, and push
).As in the C family, 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.var myArray = []; // Point the variable myArray to a newly ...
// ... created, empty Array
myArray.push("hello world"); // Fill the next empty index, in this case 0
alert(myArray[0]); // Equivalent to alert("hello world");
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.Elements of Arrays may be accessed using normal object property access notation:
myArray[1]; // the 2nd item in myArray
myArray["1"];
The above 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 6 elements, ...
// ... including 2 undefined 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 array
Sparse array
In computer science, a sparse array is an array in which most of the elements have the same value . The occurrence of zero elements in a large array is inconvenient for both computation and storage...
s". 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.One can use the object declaration literal to create objects that behave much like associative arrays in other languages:
dog = {color: "brown", size: "large"};
dog["color"]; // results in "brown"
dog.color; // also results in "brown"
One can use the object and array declaration literals to quickly create arrays that are associative, multidimensional, or both.
(Technically, JavaScript does not support multidimensional arrays, but one can mimic them with arrays-of-arrays.)
cats = [{color: "brown", size: "large"},
{color: "black", size: "small"}];
cats[0]["size"]; // results in "large"
dogs = {rover: {color: "brown", size: "large"},
spot: {color: "black", size: "small"}};
dogs["spot"]["size"]; // results in "small"
dogs.rover.color; // results in "brown"
Date
A Date object stores a signed millisecond count with zero representing 1970-01-01 00:00:00 UT and a range of ±108 days. There are several ways of providing arguments to theDate
constructor. Note that months are zero-based.new Date // create a new Date instance representing the current time/date.
new Date(2010, 2, 1) // create a new Date instance representing 2010-Mar-01 00:00:00
new Date(2010, 2, 1, 14, 25, 30) // create a new Date instance representing 2010-Mar-01 14:25:30
new Date("2010-3-1 14:25:30") // create a new Date instance from a String.
Methods to extract fields are provided, as well as a useful
toString
:var d = new Date(2010, 2, 1, 14, 25, 30); // 2010-Mar-01 14:25:30
// Displays '2010-3-1 14:25:30':
alert(d.getFullYear + '-' + (d.getMonth+1) + '-' + d.getDate + ' '
+ d.getHours + ':' + d.getMinutes + ':' + d.getSeconds);
// Built-in toString returns something like 'Mon Mar 01 2010 14:25:30 GMT-0500 (EST)':
alert(d);
Error
Custom error messages can be created using the Error class:throw new Error("Something went wrong.");
Nested within conditional statements, such instantiations can substitute for try/catch blocks:
var emailAddress = prompt("Please enter your e-mail address:", "");
if (!emailAddress || emailAddress.length 0) {
throw new Error("Excuse me: You must enter your e-mail address to continue.");
}
Math
The Math object contains various math-related constants (e.g. π) and functions (e.g. cosine). (Note the "Math" object has no constructor, unlike Array or Date. All its methods are "static" aka "class" methods.) All the trigonometric functions use angles expressed in radianRadian
Radian is the ratio between the length of an arc and its radius. The radian is the standard unit of angular measure, used in many areas of mathematics. The unit was formerly a SI supplementary unit, but this category was abolished in 1995 and the radian is now considered a SI derived unit...
s, not degrees
Degree (angle)
A degree , usually denoted by ° , is a measurement of plane angle, representing 1⁄360 of a full rotation; one degree is equivalent to π/180 radians...
or grads
Grad (angle)
The gradian is a unit of plane angle, equivalent to of a turn. It is also known as gon, grad, or grade . One grad equals of a degree or of a radian...
.
Property | Value Returned rounded to 5 digits | Description |
---|---|---|
Math.E | 2.7183 | e E (mathematical constant) The mathematical constant ' is the unique real number such that the value of the derivative of the function at the point is equal to 1. The function so defined is called the exponential function, and its inverse is the natural logarithm, or logarithm to base... : Euler's number |
Math.LN2 | 0.69315 | Natural logarithm Natural logarithm The natural logarithm is the logarithm to the base e, where e is an irrational and transcendental constant approximately equal to 2.718281828... of 2 |
Math.LN10 | 2.3026 | Natural logarithm of 10 |
Math.LOG2E | 1.4427 | Logarithm Logarithm The logarithm of a number is the exponent by which another fixed value, the base, has to be raised to produce that number. For example, the logarithm of 1000 to base 10 is 3, because 1000 is 10 to the power 3: More generally, if x = by, then y is the logarithm of x to base b, and is written... to the base 2 of e |
Math.LOG10E | 0.43429 | Logarithm to the base 10 of e |
Math.PI | 3.14159 | π Pi ' is a mathematical constant that is the ratio of any circle's circumference to its diameter. is approximately equal to 3.14. Many formulae in mathematics, science, and engineering involve , which makes it one of the most important mathematical constants... : circumference/diameter of a circle |
Math.SQRT1_2 | 0.70711 | Square root Square root In mathematics, a square root of a number x is a number r such that r2 = x, or, in other words, a number r whose square is x... of ½ |
Math.SQRT2 | 1.4142 | Square root of 2 |
Example | Value Returned rounded to 5 digits | Description |
---|---|---|
Math.abs(-2.3) | 2.3 | Absolute value: (x < 0) ? -x : x |
Math.acos(Math.SQRT1_2) | 0.78540 rad. = 45° | Arccosine |
Math.asin(Math.SQRT1_2) | 0.78540 rad. = 45° | Arcsine |
Math.atan(1) | 0.78540 rad. = 45° | Half circle arctangent (-π/2 to +π/2) |
Math.atan2(-3.7, -3.7) | -2.3562 rad. = -135° | Whole circle arctangent (-π to +π) |
Math.ceil(1.1) | 2 | Ceiling: round Rounding Rounding a numerical value means replacing it by another value that is approximately equal but has a shorter, simpler, or more explicit representation; for example, replacing $23.4476 with $23.45, or the fraction 312/937 with 1/3, or the expression √2 with 1.414.Rounding is often done on purpose to... up to smallest integer ≥ argument |
Math.cos(Math.PI/4) | 0.70711 | Cosine |
Math.exp(1) | 2.7183 | Exponential function Exponential function In mathematics, the exponential function is the function ex, where e is the number such that the function ex is its own derivative. The exponential function is used to model a relationship in which a constant change in the independent variable gives the same proportional change In mathematics,... : e raised to this power |
Math.floor(1.9) | 1 | Floor: round down to largest integer ≤ argument |
Math.log(Math.E) | 1 | Natural logarithm, base e |
Math.max(1, -2) | 1 | Maximum: (x > y) ? x : y |
Math.min(1, -2) | -2 | Minimum: (x < y) ? x : y |
Math.pow(-3, 2) | 9 | Exponentiation Exponentiation Exponentiation is a mathematical operation, written as an, involving two numbers, the base a and the exponent n... (raised to the power of): Math.pow(x, y) gives xy |
Math.random | 0.17068 | Pseudorandom number between 0 (inclusive) and 1 (exclusive) |
Math.round(1.5) | 2 | Round to the nearest integer; half fractions are rounded up (e.g. 1.5 rounds to 2) |
Math.sin(Math.PI/4) | 0.70711 | Sine |
Math.sqrt(49) | 7 | Square root |
Math.tan(Math.PI/4) | 1 | Tangent |
Regular Expression
/expression/.test(string);
"string".search(/expression/);
"string".replace(/expression/,replacement);
// Here are some examples
if(/Tom/.test("My name is Tom")) alert("Hello Tom!");
alert("My name is Tom".search(/Tom/)); //
11 (letters before Tom)
alert("My name is Tom".replace(/Tom/,"John")); //
"My name is John"Character Classes:
// \d - digit
// \D - non digit
// \s - space
// \S - non space
// \w - word char
// \W - non word
// [ ] - one of
// [^ ] - one not of
// - - range
if (/\d/.test('0')) alert('Digit');
if (/[0-9]/.test('5')) alert('Digit');
if (/[13579]/.test('1')) alert('Odd number');
if (/\S\S\s\S\S\S\S/.test('My name')) alert('Format OK');
if (/\w\w\w/.test('Tom')) alert('Format OK');
if (/[a-z]/.test('b')) alert('Small letter');
if (/[A-Z]/.test('B')) alert('Big letter');
if (/[a-zA-Z]/.test('B')) alert('Letter');
Character matching:
// A...Z a...z 0...9 - alphanumeric
// \u0000...\uFFFF - Unicode hexadecimal
// \x00...\xFF - ASCII hexadecimal
// \t - tab
// \n - new line
// \r - CR
// . - any character
// | - OR
if (/T.m/.test('Tom')) alert ('Hi Tom, Tam or Tim');
if (/A|B/.test("A")) alert ('A or B');
Repeaters:
// ? - 0 or 1 match
// * - 0 or more
// + - 1 or more
// {n} - exactly n
// {n,} - n or more
// {0,n} - n or less
// {n,m} - range n to m
if (/ab?c/.test("ac")) alert("OK"); // match: "ac", "abc"
if (/ab*c/.test("ac")) alert("OK"); // match: "ac", "abc", "abbc", "abbbc" etc.
if (/ab+c/.test("abc")) alert("OK"); // match: "abc", "abbc", "abbbc" etc.
if (/ab{3}c/.test("abbbc")) alert("OK"); // match: "abbbc"
if (/ab{3,}c/.test("abbbc")) alert("OK"); // match: "abbbc", "abbbbc", "abbbbbc" etc.
if (/ab{1,3}c/.test("abc")) alert("OK"); // match: "abc","abbc", "abbbc"
Anchors:
// ^ - string starts with
// $ - string ends with
if (/^My/.test("My name is Tom")) alert ("Hi!");
if (/Tom$/.test("My name is Tom")) alert ("Hi Tom!");
Subexpression
// - groups characters
if (/water(mark)?/.test("watermark")) alert("Here is water!"); // match: "water", "watermark",
if (/(Tom)|(John)/.test("John")) alert("Hi Tom or John!");
Flags:
// /g - global
// /i - ignore upper/lower case
// /m - allow matches to span multiple lines
alert("hi tom!".replace(/Tom/i,"John")); //
"hi John!"
alert("ratatam".replace(/ta/,"tu")); //
"ratutam"alert("ratatam".replace(/ta/g,"tu")); //
"ratutum"
Advanced methods
my_array = my_string.split(my_delimiter);
// example
my_array = "dog,cat,cow".split(","); // my_array("dog","cat","cow");
my_array = my_string.match(my_expression);
// example
my_array = "We start at 11:30, 12:15 and 16:45".match(/\d\d:\d\d/); // my_array=("11:30","12:15","16:45");
Capturing groups
var myRe = /(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})/;
var results = myRe.exec("The date and time are 2009-09-08 09:37:08.");
if (results) {
alert("Matched: " + results[0]); // Entire match
var my_date = results[1]; // First group
"2009-09-08"
var my_time = results[2]; // Second group
"09:37:08"alert("It is " + my_time + " on " + my_date);
} else alert("Did not find a valid date!");
Function
Every function in Javascript is an instance of the Function object://x,y is the argument. 'return x+y' is the function body, which is the last in the argument list.
var add = new Function('x', 'y', 'return x+y');
var t = add(1, 2);
alert(t); //3
The add function above is often defined using the following pattern, as this pattern is faster and more intuitive.
function add(x, y) {
return x + y;
}
var t = add(1, 2);
alert(t); //3
A function instance has properties and methods.
function subtract(x, y) {
return x - y;
}
alert(subtract.length);//2,expected amount of arguments.
alert(subtract.toString);
/*
function subtract(x, y) {
return x - y;
}
Operators
The '+' operator is overloadedOperator overloading
In object oriented computer programming, operator overloading—less commonly known as operator ad-hoc polymorphism—is a specific case of polymorphism, where different operators have different implementations depending on their arguments...
: it is used for string concatenation and arithmetic addition. This may cause problems when inadvertently mixing strings and numbers. As a unary operator, it can convert a numeric string to a number.
// Concatenate 2 strings
alert('He' + 'llo'); // displays Hello
// Add two numbers
alert(2 + 6); // displays 8
// Adding a number and a string results in concatenation
alert(2 + '2'); // displays 22
alert('$' + 3 + 4); // displays $34, but $7 may have been expected
alert('$' + (3 + 4)); // displays $7
// Convert a string to a number
alert(+'2'
2); // displays true
alert(+'Hello'); // displays NaN
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;
alert(++x); // displays: 2
alert(x++); // displays: 2; x becomes 3 then
alert(x); // displays: 3
alert(x--); // displays: 3; x becomes 2 then
alert(x); // displays: 2
alert(--x); // displays: 1
Assign
+= Add and assign
-= Subtract and assign
- = Multiply and assign
/= Divide and assign
%= Modulus and assign
Assignment of primitive types
var x = 1;
x *= 3;
alert(x); // displays: 3
x /= 3;
alert(x); // displays: 1
x -= 1;
alert(x); // displays: 0
Assignment of object types
var obj_1 = {a: 1};
var obj_2 = {a: 0};
var obj_3 = obj_2;// obj_3 is a reference to obj_2
obj_2.a = 2;
alert(obj_1.a + " " + obj_2.a + " " + obj_3.a); // displays 1 2 2
obj_2 = obj_1;// obj_2 now references obj_1
// obj_3 now the only reference to what was obj_2
alert(obj_1.a + " " + obj_2.a + " " + obj_3.a); // displays 1 1 2
obj_2.a = 7;// modifies obj_1
alert(obj_1.a + " " + obj_2.a + " " + obj_3.a); // displays 7 7 2
Destructuring Assignment
In Mozilla's JavaScript, since version 1.7, destructuring assignment allows the assignment of parts of data structures to several variables at once. 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.var a, b, c, d, e;
[a, b] = [3, 4];
alert(a + ',' + b); // displays: 3,4
e = {foo: 5, bar: 6, baz: ['Baz', 'Content']};
var arr = [];
({baz: [arr[0], arr[3]], foo: a, bar: b}) = e;
alert(a + ',' + b + ',' + arr); // displays: 5,6,Baz,,,Content
[a, b] = [b, a]; // swap contents of a and b
alert(a + ',' + b); // displays: 6,5
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 identicalWhen comparing variables which are objects they are considered to be different if their objects are not the same object, even if the values of them are the same, so:
var obj1 = {a: 1};
var obj2 = {a: 1};
var obj3 = obj1;
alert(obj1obj2); //false
obj1); //true
alert(obj3
See also String.
Logical
JavaScript provides four logical operators:- unary negationNegationIn logic and mathematics, negation, also called logical complement, is an operation on propositions, truth values, or semantic values more generally. Intuitively, the negation of a proposition is true when that proposition is false, and vice versa. In classical logic negation is normally identified...
(NOT = !a
) - binary disjunctionLogical disjunctionIn logic and mathematics, a two-place logical connective or, is a logical disjunction, also known as inclusive disjunction or alternation, that results in true whenever one or more of its operands are true. E.g. in this context, "A or B" is true if A is true, or if B is true, or if both A and B are...
(OR = a || b
) and conjunctionLogical conjunctionIn logic and mathematics, a two-place logical operator and, also known as logical conjunction, results in true if both of its operands are true, otherwise the value of false....
(AND = a && b
) - ternary conditional (
c ? t : f
)
In the context of a logical operation, any expression evaluates to true except the following:
-
Strings: "",
, -
Numbers: 0, -0, NaN
, -
Special: null, undefined
, -
Boolean: false
.
The Boolean function can be used to explicitly convert to a primitive of type Boolean:
// Only empty strings return false
alert(Boolean("")
false);
alert(Boolean("false")
true);alert(Boolean("0")
true);
// Only zero and NaN return false
alert(Boolean(NaN)
false);alert(Boolean(0)
false);
alert(Boolean(-0)
false); // equivalent to -1*0alert(Boolean(-2)
true );
// All objects return true
alert(Boolean(this)
true);alert(Boolean({})
true);
alert(Boolean([])
true);// These types return false
alert(Boolean(null)
false);
alert(Boolean(undefined)
false); // equivalent to BooleanThe NOT operator evaluates its operand as a Boolean, and returns the negation. Using the operator twice in a row, as a double negative
Double negative
A double negative occurs when two forms of negation are used in the same sentence. Multiple negation is the more general term referring to the occurrence of more than one negative in a clause....
, explicitly converts an expression to a primitive of type Boolean:
alert( !0
Boolean(!0)); alert(Boolean(!0)
!!1); alert(!!1 Boolean(1));
alert(!!0
Boolean(0)); alert(Boolean(0) !1); alert(!1
Boolean(!1));alert(!""
Boolean(!"")); alert(Boolean(!"")
!!"s"); alert(!!"s" Boolean("s"));
alert(!!""
Boolean("")); alert(Boolean("") !"s"); alert(!"s"
Boolean(!"s"));The ternary operator can also be used for explicit conversion:
alert([]
false); alert([] ? true : false); // “truthy” but the comparison uses [].toString
alert([0]
false); alert([0]? true : false); // [0].toString "0"
alert("0"
false); alert("0"? true : false); // "0" → 0 … (00) … 0 ← false
alert([1]
true); alert([1]? true : false); // [1].toString "1"
alert("1"
true); alert("1"? true : false); // "1" → 1 … (11) … 1 ← true
alert([2] != true); alert([2]? true : false); // [2].toString
"2"alert("2" != true); alert("2"? true : false); // "2" → 2 … (2!=1) … 1 ← true
Expressions that use features such as post–incrementation, (
i++
), have an anticipated side effectSide effect (computer science)
In computer science, a function or expression is said to have a side effect if, in addition to returning a value, it also modifies some state or has an observable interaction with calling functions or the outside world...
. JavaScript provides short-circuit evaluation of expressions; the right operand is only executed if the left operand does not suffice to determine the value of the expression.
alert(a || b); // When a is true, there is no reason to evaluate b.
alert(a && b); // When a is false, there is no reason to evaluate b.
alert(c ? t : f); // When c is true, there is no reason to evaluate f.
In early versions of JavaScript and JScript, the binary logical operators returned a Boolean value (like most C–derived programming languages). However, all contemporary implementations return one of their operands instead:
alert(a || b); // if a is true, return a, otherwise return b
alert(a && b); // if a is false, 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)"; // assigns t, or the default value if t is null, empty, etc.
Bitwise
JavaScript supports the following binary bitwise operators:
& And
| Or
^ Xor
<< Shift left (zero fill)
>> Shift right (sign-propagating); copies of the leftmost bit (sign bit) are shifted in from the
left.
>>> Shift right (zero fill)
For positive numbers, >> and >>> yield the same result.
JavaScript supports the following unary bitwise operators:
~ Not (inverts the bits)
Assignment
+ Concatenation
+= Concatenate and assign
Examples
str = "ab" + "cd"; // "abcd"
str += "e"; // "abcde"
str2 = "2"+2 // "22", not "4" or 4.
Compound statements
A pair of curly brackets { } and an enclosed sequence of statements constitute a compound statement, which can be used wherever a statement can be used.If ... else
if (expr) {
//statements;
} else if (expr2) {
//statements;
} else {
//statements;
}
Conditional operator
The conditional operator creates an expression that evaluates as one of two expressions depending on a condition. This is similar to the if statement that selects one of two statements to execute depending on a condition. I.e., the conditional operator is to expressions what if is to statements.result = condition ? expression : alternative;
is the same as:
if (condition) {
result = expression;
} else {
result = alternative;
}
Unlike the if statement, the conditional operator cannot omit its "else-branch".
Switch statement
The syntax of the JavaScript Switch statement is as follows:switch (expr) {
case SOMEVALUE:
//statements;
break;
case ANOTHERVALUE:
//statements;
break;
default:
//statements;
break;
}
break;
is optional; however, it is usually needed, since otherwise code execution will continue to the body of the nextcase
block.- Add a break statement to the end of the last case as a precautionary measure, in case additional cases are added later.
- Strings literal values can also be used for the case values.
- Expressions can be used instead of values.
case default:
is optional.- Braces are required.
For loop
The syntax of the JavaScript for loopFor loop
In computer science a for loop is a programming language statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement....
is as follows:
for (initial; condition; loop statement) {
/*
statements will be executed every time
the for{} loop cycles, while the
condition is satisfied
*/
}
or
for (initial; condition; loop statement) // one statement
For ... in loop
The syntax of the JavaScript For ... in loopForeach
For each is a computer language idiom for traversing items in a collection. Foreach is usually used in place of a standard for statement. Unlike other for loop constructs, however, foreach loops usually maintain no explicit counter: they essentially say "do this to everything in this set",...
is as follows:
for (var property_name in some_object) {
//statements using some_object[property_name];
}
- Iterates through all enumerable properties of an object.
- Iterates through all used indices of array including all user-defined properties of array object if any. Thus it may be better to use a traditional for loop with a numeric index when iterating over arrays.
- There are differences between the various web browsers with regard to which properties will be reflected with the for...in loop statement. In theory, this is controlled by an internal state property defined by the ECMAscript standard called "DontEnum", but in practice each browser returns a slightly different set of properties during introspection. It is useful to test for a given property using
if (some_object.hasOwnProperty(property_name)) { ... }
. Thus, adding a method to the array prototype withArray.prototype.newMethod = function {...}
may cause for ... in loops to loop over the method's name.
While loop
The syntax of the JavaScript while loopWhile loop
In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The while loop can be thought of as a repeating if statement....
is as follows:
while (condition) {
statement1;
statement2;
statement3;
...
}
Do ... while loop
The syntax of the JavaScript do ... while loopDo while loop
In most computer programming languages, a do while loop, sometimes just called a do loop, is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. Note though that unlike most languages, Fortran's do loop is actually analogous to the for loop.The...
is as follows:
do {
statement1;
statement2;
statement3;
...
} while (condition);
With
Thewith
statement sets the default object for the set of statements that follow.with (document) {
var a = getElementById('a');
var b = getElementById('b');
var c = getElementById('c');
};
- Note the absence of
document.
before eachgetElementById
invocation.
The semantics are similar to the
with
statement of PascalPascal (programming language)
Pascal is an influential imperative and procedural programming language, designed in 1968/9 and published in 1970 by Niklaus Wirth as a small and efficient language intended to encourage good programming practices using structured programming and data structuring.A derivative known as Object Pascal...
.
Labels
JavaScript supports nested labels in most implementations. loops or blocks can be labeled for the break statement, and loops for continue. Although gotoGoto
goto is a statement found in many computer programming languages. It is a combination of the English words go and to. It performs a one-way transfer of control to another line of code; in contrast a function call normally returns control...
is a reserved word, it does not work in JavaScript.
if (a
4) {
break loop1; // Stops after the 4th attempt
}
alert('a = ' + a);
loop2: for (var b = 0; b < 10; ++b) {
if (b
3) {continue loop2; // Number 3 is skiped
}
if (b 6) {
continue loop1; // Continues the first loop, 'finished' is not shown
}
alert('b = ' + b);
}
alert('finished')
}
block1: {
alert('hello'); // Displays 'hello'
break block1;
alert('world'); // Will never get here
}
goto block1; // Parse error.
Functions
A function is a block with a (possibly empty) parameter list that is normally given a name. A function may utilize local variables. If you exit the function without a return statement, the value
undefined
is returned.function gcd(segmentA, segmentB) {
var diff = segmentA - segmentB;
if (diff 0)
return segmentA;
return diff > 0 ? gcd(segmentB, diff) : gcd(segmentA, -diff);
}
alert(gcd(60, 40)); // 20
var mygcd=gcd; // mygcd is a reference to the same function as gcd. Note no argument s.
alert(mygcd(60, 40)); // 20
Functions are first class objects and may be assigned to other variables.
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
(which can be implicitly cast to false). Within the function, the arguments may also be accessed through the arguments
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. (While the arguments list has a .length property, it is not an instance of Array; it does not have methods such as .slice, .sort, etc.)function add7(x, y) {
if (!y) {
y = 7;
}
alert(x + y + arguments.length);
};
add7(3); // 11
add7(3, 4); // 9
All parameters are passed by value (for objects it is the reference to the object that is passed).
var obj1 = {a : 1};
var obj2 = {b : 2};
function foo(p) {
p = obj2; // ignores actual parameter
p.b = arguments[1];
}
foo(obj1, 3); // Does not affect obj1 at all. 3 is additional parameter
alert(obj1.a + " " + obj2.b); // writes 1 3
Functions can be declared inside other functions, and access the outer function's local variables. Furthermore they implement full closure
Closure (computer science)
In computer science, a closure is a function together with a referencing environment for the non-local variables of that function. A closure allows a function to access variables outside its typical scope. Such a function is said to be "closed over" its free variables...
s by remembering the outer function's local variables even after the outer function has exited.
var v = "Top";
var bar, baz;
function foo {
var v = "fud";
bar = function { alert(v) };
baz = function(x) { v = x; };
}
foo;
baz("Fugly");
bar; // Fugly (not fud) even though foo has exited.
alert(v); // Top
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 programmingPrototype-based programming
Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse is performed via a process of cloning existing objects that serve as prototypes. This model can also be known as classless, prototype-oriented or instance-based programming...
terminology). Objects may be thought of as associative arrays or hashes, and are often implemented using these data structures. However, objects have additional features, such as a prototype chain, which ordinary associative arrays do not have.
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 constructor or an object literal. The constructor can use either a built-in Object function or a custom function. It is a convention that constructor functions are given a name that starts with a capital letter:// Constructor
var anObject = new Object;
// Object literal
var objectA = {};
var objectA2 = {}; // A != A2, {}s create new objects as copies.
var objectB = {index1: 'value 1', index2: 'value 2'};
// Custom constructor (see below)
Object literals and array literals allow one to easily create flexible data structures:
var myStructure = {
name: {
first: "Mel",
last: "Smith"
},
age: 33,
hobbies: ["chess", "jogging"]
};
This is the basis for JSON
JSON
JSON , or JavaScript Object Notation, is a lightweight text-based open standard designed for human-readable data interchange. It is derived from the JavaScript scripting language for representing simple data structures and associative arrays, called objects...
, which is a simple notation that uses JavaScript-like syntax for data exchange.
Methods
A methodMethod (computer science)
In object-oriented programming, a method is a subroutine associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time...
is simply a function that is assigned to the value of an object's slot. Unlike many object-oriented languages, there is no distinction between a function definition and a method definition. Rather, the distinction occurs during function calling; a function can be called as a method.
When called as a method, the standard local variable this is just automatically set to the object instance to the left of the ".". (There are also call and apply methods that can set this explicitly—some packages such as jQuery
JQuery
jQuery is a cross-browser JavaScript library designed to simplify the client-side scripting of HTML. It was released in January 2006 at BarCamp NYC by John Resig...
do unusual things with this.)
In the example below, Foo is being used as a constructor. There is nothing special about a constructor, it is just a method that is invoked after the object is created. this is set to the newly created object.
Note that in the example below, Foo is simply assigning values to slots, some of which are functions. Thus it can assign different functions to different instances. There is no prototyping in this example.
function px {return this.prefix + "X";}
function Foo(yz) {
this.prefix = "a-";
if (yz > 0) {
this.pyz = function {return this.prefix + "Y";};
} else {
this.pyz = function {return this.prefix + "Z";};
}
this.m1 = px;
}
var foo1 = new Foo(1);
var foo2 = new Foo(0);
foo2.prefix = "b-";
alert("foo1/2 " + foo1.pyz + foo2.pyz);
// foo1/2 a-Y b-Z
foo1.m3 = px; // Assigns the function itself, not its evaluated result, i.e. not px
var baz = {"prefix": "c-"};
baz.m4 = px; // No need for a constructor to make an object.
alert("m1/m3/m4 " + foo1.m1 + foo1.m3 + baz.m4);
// m1/m3/m4 a-X a-X c-X
foo1.m2; // Throws an exception, because foo1.m2 doesn't exist.
Constructors
Constructor functions simply assign values to slots of a newly created object. The values may be data or other functions.Example: Manipulating an object
function MyObject(attributeA, attributeB) {
this.attributeA = attributeA;
this.attributeB = attributeB;
}
MyObject.staticC = "blue"; // On MyObject Function, not obj
alert(MyObject.staticC); // blue
obj = new MyObject('red', 1000);
alert(obj.attributeA); // red
alert(obj["attributeB"]); // 1000
alert(obj.staticC); // undefined
obj.attributeC = new Date; // add a new property
delete obj.attributeB; // remove a property of obj
alert(obj.attributeB); // undefined
delete obj; // remove the whole Object (rarely used)
alert(obj.attributeA); // throws an exception
The constructor itself is stored in the special slot constructor. So
function Foo{}
// use of 'new' sets prototype and constructor slots ( eg
// Foo.prototype = {}; // would set constructor to Object )
x = new Foo;
// Above is almost equivalent to
y = {};
y.constructor = Foo;
y.constructor;
// except
x.constructor y.constructor // true
x instanceof Foo // true
y instanceof Foo // false
z = new {constructor: Foo}.constructor;
z instanceof Foo // true.
// changing Foo.prototype after 'new' has been called can change the
// instanceof results, until it is changed back with the identical value
Functions are objects themselves, which can be used to produce an effect similar to "static properties" (using C++/Java terminology) as shown below. (The function object also has a special
prototype
property, as discussed in the Inheritance section below.)Object deletion is rarely used as the scripting engine will garbage collect
Garbage collection (computer science)
In computer science, garbage collection is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program...
objects that are no longer being referenced.
Inheritance
JavaScript supports inheritance hierarchies through prototyping in the manner of Self.In the following example, the Derived class inherits from the Base class.
When d is created as a Derived, the reference to the base instance of Base is copied to d.base.
Derive does not contain a value for aBaseFunction, so it is retrieved from Base when aBaseFunction is accessed.
This is made clear by changing the value of base.aBaseFunction, which is reflected in the value of d.aBaseFunction.
Some implementations allow the prototype to be accessed or set explicitly using the __proto__ slot as shown below.
function Base {
this.anOverride = function {alert("Base::anOverride");};
this.aBaseFunction = function {alert("Base::aBaseFunction");};
}
function Derived {
this.anOverride = function {alert("Derived::anOverride");};
}
base = new Base;
Derived.prototype = base; // Must be before new Derived
d = new Derived; // Copies Derived.prototype to d instance's hidden prototype slot.
base.aBaseFunction = function {alert("Base::aNEWBaseFunction")}
d.anOverride; // Derived::anOverride
d.aBaseFunction; // Base::aNEWBaseFunction
alert(d.aBaseFunction Derived.prototype.aBaseFunction); // true
alert(d.__proto__ base); // true in Mozilla-based implementations but false in many other implementations
The following shows clearly how references to prototypes are copied on instance creation, but that changes to a prototype can affect all instances that refer to it.
function m1 {return "One";}
function m2 {return "Two";}
function m3 {return "Three";}
function Base {}
Base.prototype.m = m2;
bar = new Base;
alert("bar.m " + bar.m); // bar.m Two
function Top {this.m = m3;}
t = new Top;
foo = new Base;
Base.prototype = t;
// No effect on foo, the *reference* to t is copied.
alert("foo.m " + foo.m); // foo.m Two
baz = new Base;
alert("baz.m " + baz.m); // baz.m Three
t.m = m1; // Does affect baz, and any other derived classes.
alert("baz.m1 " + baz.m); // baz.m1 One
In practice many variations of these themes are used, and it can be both powerful and confusing.
Exception handling
JavaScript includes a
try ... catch ... finally
exception handlingException handling
Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions, special conditions that change the normal flow of program execution....
statement to handle run-time errors.
The
try ... catch ... finally
statement catches exceptionsException handling
Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions, special conditions that change the normal flow of program execution....
resulting from an error or a throw statement. 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, 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. The Catch block can
throw(errorValue)
if it does not want to handle a specific error.In any case the statements in the finally block are always executed. This can be used to free resources, although memory is automatically garbage collected.
Either the
catch
or the finally
clause may be omitted. The catch argument is required.The Mozilla implementation allows for multiple catch statements, as an extension to the ECMAScript standard. They follow a syntax similar to that used in Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...
:
try { statement; }
catch (e if e "InvalidNameException") { statement; }
catch (e if e
"InvalidIdException") { statement; }
catch (e if e
"InvalidEmailException") { statement; }catch (e) { statement; }
In a browser, the
onerror
event is more commonly used to trap exceptions.onerror = function (errorValue, url, lineNr) {...; return true;};
eval (expression)
Evaluates expression string parameter, which can include assignment statements. Variables local to functions can be referenced by the expression.(function foo {
var x=7;
alert("val " + eval("x+2"));
}); // shows 9.
See also
- Comparison of JavaScript-based source code editorsComparison of Javascript-based source code editorsThis article provides basic feature comparison between some of the JavaScript-based source code editors available today. This article is not all-inclusive or necessarily up-to-date.-Overview:-List of features:...
- JavaScriptJavaScriptJavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....
External links
- A re-introduction to JavaScript - Mozilla Developer Center
- ECMAScript standard references: ECMA-262
- Interactive JavaScript Lessons - example-based
- JavaScript on About.com: lessons and explanation
- Mozilla Developer Center Core References for JavaScript versions 1.5, 1.4, 1.3 and 1.2
- Mozilla JavaScript Language Documentation
- Comparison Operators in JavaScript