Introduction To JavaScript
Introduction To JavaScript
JavaScript
DroidScript - Language
A basic introduction to the JavaScript language with the most useful and commonly used parts
of the JavaScript language. This manual is a resume offline of the web site
http://droidscript.org/javascript/index.html
9/18/2022
INTRODUCTION TO THE JAVASCRIPT
Transcribed by Gustavo Puelma – gpuelma@gmail.com
PREFACE
This book is a basic introduction to the JavaScript language with the most useful and commonly
used parts of the JavaScript language. This manual is a resume offline of the web site
http://droidscript.org/javascript/index.html
JavaScript is now one of the most popular and useful computer languages on the planet. It can be
used to create web pages, web servers, mobile Apps and even inside embedded micro-controllers!
Statements
JavaScript 'Apps' are computer programs written as lines of text. Each line of text is made up of one
or more statements, which are separated by a ';' (semi-colon) character like this:-
statement1;
statement2;
statement3;
These statements contain instructions for the computer to perform (execute) and the ';' character at
the end tells the computer where each statement ends and the next one starts.
We usually place statements on separate lines as this can help when looking for bugs (problems).
Here's a simple JavaScript program made using two statements. It displays the word "Hello" in a
popup box:
var s = "Hello";
alert( s );
Comments
You should also add comments to your programs, which are ignored by the computer but help you
and others understand what the program is supposed to be doing. To do this you use the '//' (double
forward slash) characters.
Variables
Variables are declared using the 'var' keyword and allow us to store data such as text, numbers and
objects in the computer's memory using a name of our choosing. We can then read and change the
stored data later by using the name we have given to the variable.
Note: Text data should always be enclosed in quotes or the computer will think it's a variable name.
Expressions
A statement such as myNum = myNum + 2 is an expression and we can perform various maths
and text operations on our variables using expressions.
For example:
Note: When you add a number to text, the number is automatically converted to text.
Data Types
We can store all of these types in variables and also use them in expressions, but
the Array and Object data types are special 'reference' types, which means variables containing
these types actually hold a reference (or pointer) to the original data rather than the actual data.
When you copy reference types from one variable to another, you will not get a separate copy of the
data in the computer's memory, but rather a copy of the reference.
Conditional Statements
We often want to take different actions in our program depending on certain conditions and the
easiest way to do this is using an 'if' statement like this:
Note: We use the double equals sign when we comparing variables and the single equals sign when
we are assigning (setting) variables.
In order to execute more than one statement after an 'if' or 'else' clause, we can use the '{}' (brace)
characters to group statements into a 'block' of code:
For example, in a game we might have some statements like this to check if the character has
crashed and the game is over:
Operators
We can perform various mathematical, logical and text operations in JavaScript such as add,
subtract, divide and multiply but you will often see a statement like this:
num += 2;
This may look confusing at first, but this '+=' operation simply adds 2 to the contents of variable
'num'. This is a shorter and more efficient way of writing the following:
num = num + 2;
Here are some examples of the most common operations and their meanings:
z = x * y; //z = x multiplied by y
z = x / y; //z = x divided by y
z = x % y; //z = remainder of x divided by y
num++; //add 1 to the contents of num
num--; //subtract 1 from contents of num
num += 3; //add 3 to the contents of num
num -= x; //subtract x from contents of num
num *= 9; //multiply the contents of num by 9
num /= 9; //divide the contents of num by 9
b = 7; //set b to the value 7
if( b == 4 ) //if b is equal to 4
if( b != c ) //if b is not equal to c
Another very useful operation is the ?: or 'Ternary' operation. This allows us to conditionally get one
of two possible values using a single line of code. For example:
Loops
In JavaScript we often want to repeat a block of statements many times and the two most common
ways of doing this are with the 'while' and 'for' statements.
A 'while' statement will keep repeating a block of statements while a given expression is true. For
example, the following code will keep asking the user if they are ready until they answer "yes".
var answer;
while( answer != "yes" )
{
answer = prompt( "Are you ready?" );
}
In the above sample, the counter variable 'i' starts at zero and increases by 1 each time the block of
code is complete, but only while 'i' contains a value less than 10. So the variable 'i' will range from
zero to nine.
Functions
If we find that we need to execute the same (or a similar) group of statements from various parts of
our program, then instead of copying and pasting the same group of statements all over our
program, it is far more efficient and much neater to 'wrap' a block of code up using
the 'function' statement. We can then use a single line of code to 'call' our function and execute the
block of code.
For example, if we needed to show a random number to the user and we expect to do that more
than once in our program, then we could define a function called 'ShowRandom' and call it like this:
ShowRandom();
If we want the function to behave slightly differently each time we call it, then we can pass input
values to the function. These are known as input 'parameters'.
ShowRandom( 10 );
ShowRandom( 100 );
As well as using input values, we can also get an output ('return') value from our function too, by
using the 'return' statement. This allows our function to do calculations based on the input
parameters and return a result afterwards.
We could for example create our own function to calculate the area of a circle like this:
In Javascript we don't have to place our function before the statement which uses it, so we can put it
at the bottom of our script if we prefer, like this:
String Handling
We often want to manipulate strings (text) in JavaScript and there are a number of useful methods
available to us for doing this. Note that the position of characters within a string (known as their
'index') always starts at zero.
One of the most useful string methods is the 'split' method. This allows us to split the string into
parts and store each part in an array. The split method takes a single parameter which tells the
computer which character to look for while splitting the string.
For example if we want to get the first and third names in a comma separated list of names, we do
the following:
Another very useful string method is the 'indexOf' method. This allows us to find the index (position)
of a string within another string.
For example, we might want to check if a file is a text file by searching for the string '.txt' in its file
name like this:
Statements
JavaScript applications consist of statements with an appropriate syntax. A single statement may
span multiple lines. Multiple statements may occur on a single line if each statement is separated by
a semicolon. This isn't a keyword, but a group of keywords.
Control flow
Block A block statement is used to group zero or more statements. The block is delimited by a pair
of curly brackets.
break Terminates the current loop, switch, or label statement and transfers program control to the
statement following the terminated statement.
continue
Terminates execution of the statements in the current iteration of the current or labeled loop,
and continues execution of the loop with the next iteration.
Empty An empty statement is used to provide no statement, although the JavaScript syntax would
expect one.
if...else
switch Evaluates an expression, matching the expression's value to a case clause, and executes
statements associated with that case.
try...catch
Marks a block of statements to try, and specifies a response, should an exception be thrown.
Iterations
do...while
Creates a loop that executes a specified statement until the test condition evaluates to false.
The condition is evaluated after executing the statement, resulting in the specified statement
executing at least once.
for Creates a loop that consists of three optional expressions, enclosed in parentheses and
separated by semicolons, followed by a statement executed in the loop.
for...in
Iterates over the enumerable properties of an object, in arbitrary order. For each distinct
property, statements can be executed.
for...of
Iterates over iterable objects (including arrays, array-like objects, iterators and generators),
invoking a custom iteration hook with statements to be executed for the value of each distinct
property.
while Creates a loop that executes a specified statement as long as the test condition evaluates to
true. The condition is evaluated before executing the statement.
Operators
This chapter documents many of the JavaScript language operators, expressions and keywords.
function
/ab+c/i
( ) Grouping operator.
Left-hand-side expressions
Property accessors
Unary operators
- The unary negation operator converts its operand to Number type and then negates it.
Arithmetic operators
Arithmetic operators take numerical values (either literals or variables) as their operands and return
a single numerical value.
+ Addition operator.
- Subtraction operator.
/ Division operator.
* Multiplication operator.
% Remainder operator.
Relational operators
A comparison operator compares its operands and returns a Boolean value based on whether the
comparison is true.
instanceof
Equality operators
The result of evaluating an equality operator is always of type Boolean based on whether the
comparison is true.
== Equality operator.
!= Inequality operator.
Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard
JavaScript numerical values.
| Bitwise OR.
^ Bitwise XOR.
Logical operators are typically used with boolean (logical) values, and when they are, they return a
boolean value.
|| Logical OR.
The conditional operator returns one of two values based on the logical value of the
condition.
Assignment operators
An assignment operator assigns a value to its left operand based on the value of its right operand.
= Assignment operator.
*= Multiplication assignment.
/= Division assignment.
%= Remainder assignment.
+= Addition assignment.
-= Subtraction assignment
|= Bitwise OR assignment.
Comma operator
, The comma operator allows multiple expressions to be evaluated in a single statement and
returns the result of the last expression.
This chapter documents the most useful JavaScript built-in objects, including their methods and
properties.
Value properties
These global properties return a simple value; they have no properties or methods.
Infinity
NaN
undefined
null literal
Function properties
These global functions—functions which are called globally rather than on an object—directly
return their results to the caller.
eval()
isFinite()
isNaN()
parseFloat()
parseInt()
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
These are the base objects representing numbers, dates, and mathematical calculations.
Number
Math
Date
String
RegExp
block
A block statement (or compound statement in other languages) is used to group zero or more
statements. The block is delimited by a pair of curly brackets.
Syntax
{
statement_1;
statement_2;
...
statement_n;
}
statement_1, statement_2, statement_n
Description
This statement is commonly used with control flow statements (e.g. if...else, for, while). For
example:
Note that the block statement does not end with a semicolon.
The block statement is often called compound statement in other languages. It allows you to use
multiple statements where JavaScript expects only one statement. Combining statements into blocks
No block scope
Important: Variables declared with var do not have block scope. Variables introduced with a block
are scoped to the containing function or script, and the effects of setting them persist beyond the
block itself. In other words, block statements do not introduce a scope. Although "standalone" blocks
are valid syntax, you do not want to use standalone blocks in JavaScript, because they don't do what
you think they do, if you think they do anything like such blocks in C or Java. For example:
var x = 1;
{
var x = 2;
}
console.log(x); // logs 2
This logs 2 because the var x statement within the block is in the same scope as the var
x statement before the block. In C or Java, the equivalent code would have outputted 1.
break
The break statement terminates the current loop, switch, or label statement and transfers program
control to the statement following the terminated statement.
Syntax
break [label];
label
Optional. Identifier associated with the label of the statement. If the statement is not a loop
or switch, this is required.
Description
The break statement includes an optional label that allows the program to break out of a labeled
statement. The break statement needs to be nested within the referenced label. The labeled
statement can be any block statement; it does not have to be preceded by a loop statement.
The following function has a break statement that terminates the while loop when i is 3, and then
returns the value 3 * x.
function testBreak(x) {
var i = 0;
while (i < 6) {
if (i == 3) {
break;
}
i += 1;
}
return i * x;
}
The following code uses break statements with labeled blocks. A break statement must be nested
within any label it references. Notice that inner_block is nested within outer_block.
outer_block: {
inner_block: {
console.log('1');
break outer_block; // breaks out of both inner_block and outer_block
console.log(':-('); // skipped
}
console.log('2'); // skipped
}
The following code also uses break statements with labeled blocks but generates a Syntax Error
because its break statement is within block_1 but references block_2. A break statement must
always be nested within any label it references.
block_1: {
console.log('1');
break block_2; // SyntaxError: label not found
block_2: {
console.log('2');
}
continue
The continue statement terminates execution of the statements in the current iteration of the
current or labeled loop, and continues execution of the loop with the next iteration.
Syntax
continue [label];
label
Description
In contrast to the break statement, continue does not terminate the execution of the loop entirely:
instead,
The continue statement can include an optional label that allows the program to jump to the next
iteration of a labeled loop statement instead of the current loop. In this case, the continue statement
needs to be nested within this labeled statement.
Examples
The following example shows a while loop that has a continue statement that executes when the
value of i is 3. Thus, n takes on the values 1, 3, 7, and 12.
var i = 0;
while (i < 5) {
i++;
if (i === 3) {
continue;
}
n += i;
}
In the following example, a statement labeled checkiandj contains a statement labeled checkj.
If continue is encountered, the program continues at the top of the checkj statement. Each
time continue is encountered, checkj reiterates until its condition returns false. When false is
returned, the remainder of the checkiandj statement is completed.
If continue had a label of checkiandj, the program would continue at the top of
the checkiandj statement.
var i = 0;
var j = 8;
if ((j % 2) == 0)
continue checkj;
Output:
"i: 0"
// start checkj
"j: 8"
"7 is odd."
"j: 7"
"j: 6"
"5 is odd."
"j: 5"
// end checkj
"i = 1"
"j = 4"
"i: 1"
"i = 2"
"j = 4"
"i: 2"
"i = 3"
"j = 4"
"i: 3"
"i = 4"
"j = 4"
An empty statement is used to provide no statement, although the JavaScript syntax would expect
one.
Syntax
;
Description
The empty statement is a semicolon (;) indicating that no statement will be executed, even if
JavaScript syntax requires one. The opposite behavior, where you want multiple statements, but
JavaScript only allows a single one, is possible using a block statement; it combines several
statements into a single one.
Examples
The empty statement is sometimes used with loop statements. See the following example with an
empty loop body:
console.log(arr)
// [0, 0, 0]
Note: It is a good idea to comment the intentional use of the empty statement, as it is not really
obvious to distinguish between a normal semicolon. In the following example the usage is probably
not intentional:
Another Example: An if...else statement without curly braces ({}). If three is true, nothing will
happen, four does not matter, and also the launchRocket() function in the else case will not be
executed.
if...else
The if statement executes a statement if a specified condition is true. If the condition is false,
another statement can be executed.
Syntax
if (condition)
statement1
[else
statement2]
condition
statement1
Statement that is executed if condition evaluates to true. Can be any statement, including
further nested if statements. To execute multiple statements, use a block statement ({ ... })
to group those statements, to execute no statements, use an empty statement.
statement2
Statement that is executed if condition evaluates to false and the else clause exists. Can
be any statement, including block statements and further nested if statements.
Multiple if...else statements can be nested to create an else if clause. Note that there is
no elseif (in one word) keyword in JavaScript.
if (condition1)
statement1
else if (condition2)
statement2
else if (condition3)
statement3
...
else
statementN
To see how this works, this is how it would look like if the nesting were properly indented:
if (condition1)
statement1
else
if (condition2)
statement2
else
if (condition3)
...
To execute multiple statements within a clause, use a block statement ({ ... }) to group those
statements. In general, it is a good practice to always use block statements, especially in code
involving nested if statements:
if (condition) {
statements1
} else {
statements2
}
Examples
Using if...else
Using else if
Note that there is no elseif syntax in JavaScript. However, you can write it with a space
between else and if:
if (x > 5) {
} else {
It is advisable to not use simple assignments in a conditional expression, because the assignment
can be confused with equality when glancing over the code. For example, do not use the following
code:
If you need to use an assignment in a conditional expression, a common practice is to put additional
parentheses around the assignment. For example:
if ((x = y)) {
/* do the right thing */
}
switch
The switch statement evaluates an expression, matching the expression's value to a case clause,
and executes statements associated with that case.
Syntax
switch (expression) {
case value1:
//Statements executed when the result of expression matches value1
[break;]
case value2:
//Statements executed when the result of expression matches value2
[break;]
...
case valueN:
//Statements executed when the result of expression matches valueN
[break;]
default:
//Statements executed when none of the values match the value of the
expression
[break;]
}
expression
case valueN
Description
A switch statement first evaluates its expression. It then looks for the first case clause whose
expression evaluates to the same value as the result of the input expression (using strict
comparison, ===) and transfers control to that clause, executing the associated statements. (If
multiple cases match the provided value, the first case that matches is selected, even if the cases
are not equal to each other.) If no matching case clause is found, the program looks for the
optional default clause, and if found, transfers control to that clause, executing the associated
statements. If no default clause is found, the program continues execution at the statement
following the end of switch. By convention, the default clause is the last clause, but it does not
need to be so.
The optional break statement associated with each case label ensures that the program breaks out
of switch once the matched statement is executed and continues execution at the statement
following switch. If break is omitted, the program continues execution at the next statement in
the switch statement.
Examples
Using switch
In the following example, if expr evaluates to "Bananas", the program matches the value with case
"Bananas" and executes the associated statement. When break is encountered, the program breaks
out of switch and executes the statement following switch. If break were omitted, the statement for
case "Cherries" would also be executed.
switch (expr) {
case "Oranges":
console.log("Oranges are $0.59 a pound.");
break;
case "Apples":
console.log("Apples are $0.32 a pound.");
break;
case "Bananas":
console.log("Bananas are $0.48 a pound.");
If you forget a break then script will run from the case where criteria is met, and will run the case
after that regardless if criteria was met. See example here:
var foo = 0;
switch (foo) {
case -1:
console.log('negative 1');
break;
case 0: // foo is 0 so criteria met here so this block will run
console.log(0);
// NOTE: the forgotten break would have been here
case 1: // no break statement in 'case 0:' so this case will run as well
console.log(1);
break; // it encounters this break so will not continue into 'case 2:'
case 2:
console.log(2);
break;
default:
console.log('default');
}
This method takes advantage of the fact that if there is no break below a case statement it will
continue to execute the next case statement regardless if the case meets the criteria. See the
section title "What happens if I forgot a break?"
This is an example of a single operation sequential switch statement, where four different values
perform exactly the same.
var foo = 1;
var output = 'Output: ';
switch (foo) {
throw
The throw statement throws a user-defined exception. Execution of the current function will stop
(the statements after throw won't be executed), and control will be passed to the first catch block in
the call stack. If no catch block exists among caller functions, the program will terminate.
Syntax
throw expression;
expression
Description
Use the throw statement to throw an exception. When you throw an exception, expression specifies
the value of the exception. Each of the following throws an exception:
Also note that the throw statement is affected by automatic semicolon insertion (ASI) as no line
terminator between the throw keyword and the expression is allowed.
Examples
Throw an object
You can specify an object when you throw an exception. You can then reference the object's
properties in the catch block. The following example creates an object of type UserException and
uses it in a throw statement.
function UserException(message) {
this.message = message;
this.name = "UserException";
}
function getMonthName(mo) {
mo = mo-1; // Adjust month number for array index (1=Jan, 12=Dec)
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
"Aug", "Sep", "Oct", "Nov", "Dec"];
if (months[mo] !== undefined) {
return months[mo];
} else {
throw new UserException("InvalidMonthNo");
}
}
try {
// statements to try
var myMonth = 15; // 15 is out of bound to raise the exception
monthName = getMonthName(myMonth);
} catch (e) {
monthName = "unknown";
logMyErrors(e.message, e.name); // pass exception object to err handler
The following example tests an input string for a U.S. zip code. If the zip code uses an invalid format,
the throw statement throws an exception by creating an object of type ZipCodeFormatException.
/*
* Creates a ZipCode object.
*
* Accepted formats for a zip code are:
* 12345
* 12345-6789
* 123456789
* 12345 6789
*
* If the argument passed to the ZipCode constructor does not
* conform to one of these patterns, an exception is thrown.
*/
function ZipCode(zip) {
zip = new String(zip);
pattern = /[0-9]{5}([- ]?[0-9]{4})?/;
if (pattern.test(zip)) {
// zip code value will be the first match in the string
this.value = zip.match(pattern)[0];
this.valueOf = function() {
return this.value
};
this.toString = function() {
return String(this.value)
};
} else {
throw new ZipCodeFormatException(zip);
}
}
/*
* This could be in a script that validates address data
* for US addresses.
*/
function verifyZipCode(z) {
try {
z = new ZipCode(z);
} catch (e) {
if (e instanceof ZipCodeFormatException) {
return ZIPCODE_INVALID;
} else {
return ZIPCODE_UNKNOWN_ERROR;
}
}
return z;
}
You can use throw to rethrow an exception after you catch it. The following example catches an
exception with a numeric value and rethrows it if the value is over 50. The rethrown exception
propagates up to the enclosing function or to the top level so that the user sees it.
try {
throw n; // throws an exception with a numeric value
} catch (e) {
if (e <= 50) {
// statements to handle exceptions 1-50
} else {
// cannot handle this exception, so rethrow
throw e;
}
}
try...catch
The try...catch statement marks a block of statements to try, and specifies a response, should an
exception be thrown.
Syntax
try {
try_statements
}
[catch (exception_var_1 if condition_1) { // non-standard
catch_statements_1
}]
...
[catch (exception_var_2) {
catch_statements_2
}]
[finally {
finally_statements
}]
try_statements
catch_statements_1, catch_statements_2
exception_var_1, exception_var_2
condition_1
A conditional expression.
finally_statements
Statements that are executed after the try statement completes. These statements execute
regardless of whether or not an exception was thrown or caught.
Description
The try statement consists of a try block, which contains one or more statements, and at least
one catch clause or a finally clause, or both. That is, there are three forms of the try statement:
1. try...catch
2. try...finally
3. try...catch...finally
A catch clause contain statements that specify what to do if an exception is thrown in the try block.
That is, you want the try block to succeed, and if it does not succeed, you want control to pass to
the catch block. If any statement within the try block (or in a function called from within
the try block) throws an exception, control immediately shifts to the catch clause. If no exception is
thrown in the try block, the catch clause is skipped.
The finally clause executes after the try block and catch clause(s) execute but before the
statements following the try statement. It always executes, regardless of whether or not an
exception was thrown or caught.
You can nest one or more try statements. If an inner try statement does not have a catch clause,
the enclosing try statement's catch clause is entered.
When a single, unconditional catch clause is used, the catch block is entered when any exception is
thrown. For example, when the exception occurs in the following code, control transfers to
the catch clause.
try {
You can also use one or more conditional catch clauses to handle specific exceptions. In this case,
the appropriate catch clause is entered when the specified exception is thrown. In the following
example, code in the try block can potentially throw three exceptions: TypeError, RangeError,
and EvalError. When an exception occurs, control transfers to the appropriate catch clause. If the
exception is not one of the specified exceptions and an unconditional catch clause is found, control
transfers to that catch clause.
If you use an unconditional catch clause with one or more conditional catch clauses, the
unconditional catch clause must be specified last. Otherwise, the unconditional catch clause will
intercept all types of exception before they can reach the conditional ones.
try {
myroutine(); // may throw three types of exceptions
} catch (e if e instanceof TypeError) {
// statements to handle TypeError exceptions
And here is how to do implement the same "Conditional catch clauses" using only simple JavaScript
conforming to the ECMAScript specification (obviously it's more verbose, but works everywhere):
try {
myroutine(); // may throw three types of exceptions
} catch (e) {
if (e instanceof TypeError) {
// statements to handle TypeError exceptions
} else if (e instanceof RangeError) {
// statements to handle RangeError exceptions
} else if (e instanceof EvalError) {
// statements to handle EvalError exceptions
} else {
// statements to handle any unspecified exceptions
logMyErrors(e); // pass exception object to error handler
}
}
When an exception is thrown in the try block, exception_var (e.g. the e in catch (e)) holds the
value specified by the throw statement. You can use this identifier to get information about the
exception that was thrown.
This identifier is local to the catch clause. That is, it is created when the catch clause is entered,
and after the catch clause finishes executing, the identifier is no longer available.
You can use the finally clause to make your script fail gracefully when an exception occurs; for
example, you may need to release a resource that your script has tied up. The following example
opens a file and then executes statements that use the file (server-side JavaScript allows you to
access files). If an exception is thrown while the file is open, the finally clause closes the file
before the script fails. The code in finally also executes upon explicitly returning
from try or catch block.
openMyFile()
try {
// tie up a resource
writeMyFile(theData);
}
finally {
closeMyFile(); // always close the resource
}
Examples
Nested try-blocks
try {
try {
throw new Error("oops");
}
finally {
console.log("finally");
}
}
catch (ex) {
console.error("outer", ex.message);
// Output:
// "finally"
// "outer" "oops"
Now, if we already caught the exception in the inner try-block by adding a catch block
try {
try {
throw new Error("oops");
}
catch (ex) {
console.error("inner", ex.message);
}
finally {
console.log("finally");
}
}
catch (ex) {
console.error("outer", ex.message);
}
// Output:
// "inner" "oops"
// "finally"
try {
try {
throw new Error("oops");
}
catch (ex) {
console.error("inner", ex.message);
throw ex;
}
// Output:
// "inner" "oops"
// "finally"
// "outer" "oops"
Any given exception will be caught only once by the nearest enclosing catch-block, unless it is re-
thrown. Of course, any new exceptions raised in the "inner" block (because code in catch-block may
do something that throws), will be caught by the "outer" block.
If the finally block returns a value, this value becomes the return value of the entire try-catch-
finally production, regardless of any return statements in the try and catch blocks. This includes
exceptions thrown inside of the catch block:
try {
try {
throw new Error("oops");
}
catch (ex) {
console.error("inner", ex.message);
throw ex;
}
finally {
console.log("finally");
return;
}
}
catch (ex) {
// Output:
// "inner" "oops"
// "finally"
The outer "oops" is not thrown because of the return in the finally block. The same would apply to
any value returned from the catch block.
var
Syntax
var varname1 [= value1 [, varname2 [, varname3 ... [, varnameN]]]];
varnameN
valueN
Description
Variable declarations, wherever they occur, are processed before any code is executed. The scope
of a variable declared with var is its current execution context, which is either the enclosing function
or, for variables declared outside any function, global.
Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a
property of the global object) when the assignment is executed. The differences between declared
and undeclared variables are:
1. Declared variables are constrained in the execution context in which they are declared.
Undeclared variables are always global.
function x() {
y = 1; // Throws a ReferenceError in strict mode
2. Declared variables are created before any code is executed. Undeclared variables do not exist
until the code assigning to them is executed.
3. Declared variables are a non-configurable property of their execution context (function or global).
Undeclared variables are configurable (e.g. can be deleted).
var a = 1;
b = 2;
Because of these three differences, failure to declare variables will very likely lead to unexpected
results. Thus it is recommended to always declare variables, regardless of whether they are in
a function or global scope. And in ECMAScript 5 strict mode, assigning to an undeclared variable
throws an error.
var hoisting
bla = 2
var bla;
// ...
var bla;
bla = 2;
For that reason, it is recommended to always declare variables at the top of their scope (the top of
global code and the top of function code) so it's clear which variables are function scoped (local) and
which are resolved on the scope chain.
Examples
var a = 0, b = 0;
var a = "A";
var b = a;
// Equivalent to:
var a, b = a = "A";
var x = y, y = 'A';
console.log(x + y); // undefinedA
var x = 0;
function f(){
var x = y = 1; // x is declared locally. y is not!
}
f();
console.log(x, y); // 0, 1
// x is the global one as expected
// y leaked outside of the function, though!
Variables that appear to be implicit globals may be references to variables in an outer function
scope:
console.log(x, y); // 0 2
console.log(x, z); // 3 5
console.log(typeof y); // undefined as y is local to function a
function
You can also define functions using the Function constructor and a function expression.
Syntax
function name([param,[, param,[..., param]]]) {
[statements]
}
Name The function name.
Param The name of an argument to be passed to the function. A function can have up to 255
arguments.
statements
Description
A function created with a function declaration is a Function object and has all the properties,
methods and behavior of Function objects. See Function for detailed information on functions.
Functions can be conditionally declared, that is, a function statement can be nested within
an if statement. Most browsers other than Mozilla will treat such conditional declarations as an
unconditional declaration and create the function whether the condition is true or not, see this article
for an overview. Therefore they should not be used, for conditional creation use function
expressions.
Function declarations in JavaScript are hoisting the function definition. You can use the function
before you declared it:
function hoisted() {
console.log("foo");
}
Examples
Using function
The following code declares a function that returns the total amount of sales, when given the number
of units sold of products a, b, and c.
return
The return statement ends function execution and specifies a value to be returned to the function
caller.
Syntax
return [[expression]];
expression
Description
When a return statement is called in a function, the execution of this function is stopped. If
specified, a given value is returned to the function caller. If the expression is omitted, undefined is
returned instead. The following return statements all break the function execution:
return;
return true;
return false;
return x;
return x + y / 3;
The return statement is affected by automatic semicolon insertion (ASI). No line terminator is
allowed between the return keyword and the expression.
return
a + b;
return;
Starting with Gecko 40 , a warning is shown in the console if unreachable code is found after a
return statement.
Examples
return
The following function returns the square of its argument, x, where x is a number.
function square(x) {
return x * x;
}
Interrupt a function
function counter() {
for (var count = 1; ; count++) { // infinite loop
console.log(count + "A"); // until 5
if (count === 5) {
return;
}
console.log(count + "B"); // until 4
}
console.log(count + "C"); // never appears
}
counter();
// Output:
// 1A
// 1B
Returning a function
function magic(x) {
return function calc(x) { return x * 42 };
}
do...while
The do...while statement creates a loop that executes a specified statement until the test
condition evaluates to false. The condition is evaluated after executing the statement, resulting in the
specified statement executing at least once.
Syntax
do
statement
while (condition);
statement
A statement that is executed at least once and is re-executed each time the condition
evaluates to true. To execute multiple statements within the loop, use a block statement ({
... }) to group those statements.
condition
Examples
Using do...while
In the following example, the do...while loop iterates at least once and reiterates until i is no
longer less than 5.
var i = 0;
do {
i += 1;
console.log(i);
} while (i < 5);
for
The for statement creates a loop that consists of three optional expressions, enclosed in
parentheses and separated by semicolons, followed by a statement or a set of statements executed
in the loop.
Syntax
for ([initialization]; [condition]; [final-expression])
statement
initialization
condition
final-expression
An expression to be evaluated at the end of each loop iteration. This occurs before the next
evaluation of condition. Generally used to update or increment the counter variable.
statement
A statement that is executed as long as the condition evaluates to true. To execute multiple
statements within the loop, use a block statement ({ ... }) to group those statements. To
execute no statement within the loop, use an empty statement (;).
Examples
Using for
The following for statement starts by declaring the variable i and initializing it to 0. It checks that i is
less than nine, performs the two succeeding statements, and increments i by 1 after each pass
through the loop.
All three expressions in the head of the for loop are optional.
var i = 0;
for (; i < 9; i++) {
console.log(i);
// more statements
}
You can also omit all three blocks. Again, make sure to use a break statement to end the loop and
also modify (increase) a variable, so that the condition for the break statement is true at some point.
var i = 0;
for (;;) {
if (i > 3) break;
console.log(i);
i++;
}
The following for cycle calculates the offset position of a node in the [final-expression] section, and
therefore it does not require the use of a statement or block statement section, an empty
statement is used instead.
// Example call:
showOffsetPos("content");
// Output:
// "Offset position of "content" element:
// left: 0px;
// top: 153px;"
Note: In this case, when you do not use the statement section, a semicolon is put immediately
after the declaration of the cycle.
for...in
The for...in statement iterates over the enumerable properties of an object, in arbitrary order. For
each distinct property, statements can be executed.
Syntax
for (variable in object) {...
}
variable
object
Description
A for...in loop only iterates over enumerable properties. Objects created from built–in
constructors like Array and Object have inherited non–enumerable properties
from Object.prototype and String.prototype, such as String's indexOf() method
or Object's toString() method. The loop will iterate over all enumerable properties of the object itself
and those the object inherits from its constructor's prototype (properties closer to the object in the
prototype chain override prototypes' properties).
A for...in loop iterates over the properties of an object in an arbitrary order (see
the delete operator for more on why one cannot depend on the seeming orderliness of iteration, at
least in a cross-browser setting). If a property is modified in one iteration and then visited at a later
time, its value in the loop is its value at that later time. A property that is deleted before it has been
visited will not be visited later. Properties added to the object over which iteration is occurring may
either be visited or omitted from iteration. In general it is best not to add, modify or remove properties
from the object during iteration, other than the property currently being visited. There is no guarantee
whether or not an added property will be visited, whether a modified property (other than the current
one) will be visited before or after it is modified, or whether a deleted property will be visited before it
is deleted.
Note: for...in should not be used to iterate over an Array where the index order is important.
Array indexes are just enumerable properties with integer names and are otherwise identical to
general Object properties. There is no guarantee that for...in will return the indexes in any
particular order and it will return all enumerable properties, including those with non–integer
names and those that are inherited.
Because the order of iteration is implementation-dependent, iterating over an array may not visit
elements in a consistent order. Therefore it is better to use a for loop with a numeric index
(or Array.prototype.forEach() or the for...of loop) when iterating over arrays where the order of
access is important.
If you only want to consider properties attached to the object itself, and not its prototypes,
use getOwnPropertyNames() or perform a hasOwnProperty() check (propertyIsEnumerable can
also be used). Alternatively, if you know there won't be any outside code interference, you can
extend built-in prototypes with a check method.
The following function takes as its argument an object. It then iterates over all the object's
enumerable properties and returns a string of the property names and their values.
// Output:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"
The following function illustrates the use of hasOwnProperty(): the inherited properties are not
displayed.
function ColoredTriangle() {
this.color = "red";
}
ColoredTriangle.prototype = triangle;
// Output:
// "obj.color = red"
Prior to SpiderMonkey 40 , it was possible to use an initializer expression (i=0) in a for...in loop:
This non-standard behavior is now ignored in version 40 and later and will present
a SyntaxError ("for-in loop head declarations may not have initializers") warning in the console ( and
).
Other engines like v8 (Chrome), Chakra (IE/Edge), and JSC (WebKit/Safari) are investigating to
remove the non-standard behavior as well.
for...of
Syntax
for (variable of object) {
statement
}
variable
object
The following example shows the difference between a for...of loop and a for...in loop.
While for...in iterates over property names, for...of iterates over property values:
Using Array.prototype.forEach()
To get the same property values the for...of loop would return, you can also use
the Array.prototype.forEach() method:
// or with Object.keys()
Iterating over DOM collections like : the following example adds a read class to paragraphs that are
direct descendants of an article:
The while statement creates a loop that executes a specified statement as long as the test
condition evaluates to true. The condition is evaluated before executing the statement.
Syntax
while (condition) {
statement
}
condition
An expression evaluated before each pass through the loop. If this condition evaluates to
true, statement is executed. When condition evaluates to false, execution continues with the
statement after the while loop.
statement
A statement that is executed as long as the condition evaluates to true. To execute multiple
statements within the loop, use a block statement ({ ... }) to group those statements.
Examples
var n = 0;
var x = 0;
while (n < 3) {
n++;
x += n;
}
Each iteration, the loop increments n and adds it to x. Therefore, x and n take on the following
values:
function
Syntax
function [name]([param1[, param2[, ..., paramN]]]) {
statements
}
Parameters
Name The function name. Can be omitted, in which case the function is anonymous. The name is
only local to the function body.
statements
Description
A function expression is very similar to and has almost the same syntax as a function statement (see
function statement for details). The main difference between a function expression and a function
statement is the function name, which can be omitted in function expressions to
create anonymous functions. See also the chapter about functions for more information.
Examples
The following example defines an unnamed function and assigns it to x. The function returns the
square of its argument:
var x = function(y) {
return y * y;
};
If you want to refer to the current function inside the function body, you need to create a named
function expression. This name is then local only to the function body (scope). This also avoids using
the non-standard arguments.callee property.
var math = {
'factorial': function factorial(n) {
if (n <= 1)
return 1;
return n * factorial(n - 1);
}
};
Array
Summary
The JavaScript Array object is a global object that is used in the construction of arrays; which are
high-level, list-like objects.
Create an Array
console.log(fruits.length);
// 2
fruits.push("Mango");
// ["Strawberry", "Banana", "Mango"]
Syntax
[element0, element1, ..., elementN]
new Array(element0, element1[, ...[, elementN]])
new Array(arrayLength)
elementN
A JavaScript array is initialized with the given elements, except in the case where a single
argument is passed to the Array constructor and that argument is a number. (See below.)
Note that this special case only applies to JavaScript arrays created with
the Array constructor, not array literals created with the bracket syntax.
arrayLength
If the only argument passed to the Array constructor is an integer between 0 and 232-1
(inclusive), this returns a new JavaScript array with length set to that number. If the argument
is any other number, a RangeError exception is thrown.
Description
Arrays are list-like objects whose prototype has methods to perform traversal and mutation
operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an
array's size length grow or shrink at any time, JavaScript arrays are not guaranteed to be dense. In
general, these are convenient characteristics; but if these features are not desirable for your
particular use, you might consider using typed arrays.
Some people think that you shouldn't use an array as an associative array. In any case, you can use
plain objects instead, although doing so comes with its own caveats. See the post Lightweight
JavaScript dictionaries with arbitrary keys as an example.
JavaScript arrays are zero-indexed: the first element of an array is at index 0, and the last element is
at the index equal to the value of the array's length property minus 1.
Array elements are object properties in the same way that toString is a property, but trying to
access an element of an array as follows throws a syntax error, because the property name is not
valid:
There is nothing special about JavaScript arrays and the properties that cause this. JavaScript
properties that begin with a digit cannot be referenced with dot notation; and must be accessed
using bracket notation. For example, if you had an object with a property named '3d', it can only be
referenced using bracket notation. E.g.:
Note that in the 3d example, '3d' had to be quoted. It's possible to quote the JavaScript array
indexes as well (e.g., years['2'] instead of years[2]), although it's not necessary. The 2
in years[2] is coerced into a string by the JavaScript engine through an
implicit toString conversion. It is for this reason that '2' and '02' would refer to two different slots
on the years object and the following example could be true:
console.log(years['2'] != years['02']);
Similarly, object properties which happen to be reserved words(!) can only be accessed as string
literals in bracket notation(but it can be accessed by dot notation in firefox 40.0a2 at least):
var promise = {
'var' : 'text',
'array': [1, 2, 3, 4]
};
A JavaScript array's length property and numerical properties are connected. Several of the built-in
array methods (e.g., join, slice, indexOf, etc.) take into account the value of an
array's length property when they're called. Other methods (e.g., push, splice, etc.) also result in
updates to an array's length property.
console.log(fruits.length); // 3
When setting a property on a JavaScript array when the property is a valid array index and that
index is outside the current bounds of the array, the engine will update the array's length property
accordingly:
fruits[5] = 'mango';
console.log(fruits[5]); // 'mango'
console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
console.log(fruits.length); // 6
fruits.length = 10;
console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
console.log(fruits.length); // 10
fruits.length = 2;
console.log(Object.keys(fruits)); // ['0', '1']
console.log(fruits.length); // 2
The properties and elements returned from this match are as follows:
[0] A read-only element that specifies the last matched characters. dbBd
Properties
Array.length
Array.prototype
Array instances
All Array instances inherit from Array.prototype. The prototype object of the Array constructor can
be modified to affect all Array instances.
Properties
Methods
Mutator methods
Accessor methods
Iteration methods
Array generics are non-standard, deprecated and will get removed near future. Note that you
can not rely on them cross-browser. However, there is a shim available on GitHub.
Sometimes you would like to apply array methods to strings or other array-like objects (such as
function arguments). By doing this, you treat a string as an array of characters (or otherwise treat a
non-array as an array). For example, in order to check that every character in the variable str is a
letter, you would write:
function isLetter(character) {
return character >= 'a' && character <= 'z';
}
if (Array.prototype.every.call(str, isLetter)) {
console.log("The string '" + str + "' contains only letters!");
}
if (Array.every(str, isLetter)) {
console.log("The string '" + str + "' contains only letters!");
}
These are not part of ECMAScript standards (though the ES6 Array.from() can be used to achieve
this). The following is a shim to allow its use in all browsers:
// Assumes Array extras already present (one may use polyfills for these
as well)
(function() {
'use strict';
var i,
// We could also build the array of methods with the following, but
the
// getOwnPropertyNames() method is non-shimable:
// Object.getOwnPropertyNames(Array).filter(function(methodName) {
// return typeof Array[methodName] === 'function'
// });
methods = [
'join', 'reverse', 'sort', 'push', 'pop', 'shift', 'unshift',
'splice', 'concat', 'slice', 'indexOf', 'lastIndexOf',
'forEach', 'map', 'reduce', 'reduceRight', 'filter',
'some', 'every', 'find', 'findIndex', 'entries', 'keys',
'values', 'copyWithin', 'includes'
],
methodCount = methods.length,
assignArrayGeneric = function(methodName) {
if (!Array[methodName]) {
var method = Array.prototype[methodName];
if (typeof method === 'function') {
Array[methodName] = function() {
return method.call.apply(method, arguments);
Examples
Creating an array
The following example creates an array, msgArray, with a length of 0, then assigns values
to msgArray[0] and msgArray[99], changing the length of the array to 100.
The following creates a chess board as a two dimensional array of strings. The first move is made by
copying the 'p' in (6,4) to (4,4). The old position (6,4) is made blank.
var board = [
['R','N','B','Q','K','B','N','R'],
['P','P','P','P','P','P','P','P'],
[' ',' ',' ',' ',' ',' ',' ',' '],
[' ',' ',' ',' ',' ',' ',' ',' '],
[' ',' ',' ',' ',' ',' ',' ',' '],
[' ',' ',' ',' ',' ',' ',' ',' '],
console.log(board.join('\n') + '\n\n');
R,N,B,Q,K,B,N,R
P,P,P,P,P,P,P,P
, , , , , , ,
, , , , , , ,
, , , , , , ,
, , , , , , ,
p,p,p,p,p,p,p,p
r,n,b,q,k,b,n,r
R,N,B,Q,K,B,N,R
P,P,P,P,P,P,P,P
, , , , , , ,
, , , , , , ,
, , , ,p, , ,
, , , , , , ,
p,p,p,p, ,p,p,p
r,n,b,q,k,b,n,r
Object initializer
Objects can be initialized using new Object(), Object.create(), or using the literal notation
(initializer notation). An object initializer is a list of zero or more pairs of property names and
associated values of an object, enclosed in curly braces ({}).
var o = {
property: function ([parameters]) {},
get property() {},
set property(value) {},
};
Please see the compatibility table for support for these notations. In non-supporting environments,
these notations will lead to syntax errors.
An object initializer is an expression that describes the initialization of an Object. Objects consist
of properties, which are used to describe an object. Values of object properties can either contain
primitive data types or other objects.
Creating objects
However, the advantage of the literal or initializer notation is, that you are able to quickly create
objects with properties inside the curly braces. You simply notate a list of key: value pairs delimited
by comma. The following code creates an object with three properties and the keys are "foo", "age"
and "baz". The values of these keys are a string "bar", a number 42 and the third property has
another object as its value.
var object = {
foo: "bar",
age: 42,
baz: { myProp: 12 },
}
Accessing properties
Once you have created an object, you might want to read or change them. Object properties can be
accessed by using the dot notation or the bracket notation. See property accessors for detailed
information.
object.foo; // "bar"
object["age"]; // 42
object.foo = "baz";
Property definitions
var a = "foo",
b = 42,
c = {};
var o = {
a: a,
b: b,
c: c
};
var a = "foo",
b = 42,
c = {};
When using the same name for your properties, the second property will overwrite the first.
In ECMAScript 5 strict mode code, duplicate property names were considered a SyntaxError. With
the introduction of computed property names making duplication possible at runtime, ECMAScript 6
has removed this restriction.
function haveES6DuplicatePropertySemantics(){
"use strict";
try {
({ prop: 1, prop: 2 });
Method definitions
var o = {
property: function ([parameters]) {},
get property() {},
set property(value) {},
};
In ECMAScript 6 There is a way to concisely define properties whose values are generator
functions:
var o = {
* generator() {
...........
}
};
var o = {
generatorMethod: function *() {
...........
}
};
For more information and examples about methods, see method definitions.
Starting with ECMAScript 6, the object initializer syntax also supports computed property names.
That allows you to put an expression in brackets [], that will be computed as the property name.
This is symmetrically to the bracket notation of the property accessor syntax, which you might have
used to read and set properties already. Now you can use the same syntax in object literals, too:
console.log(a.foo1); // 1
console.log(a.foo2); // 2
console.log(a.foo3); // 3
A property definition of the form __proto__: value or "__proto__": value does not create a
property with the name __proto__. Instead, if the provided value is an object or null, it changes
the [[Prototype]] of the created object to that value. (If the value is not an object or null, the object
is not changed.)
Only a single prototype mutation is permitted in an object literal: multiple prototype mutations are a
syntax error.
Property definitions that do not use "colon" notation are not prototype mutations: they are property
definitions that behave identically to similar definitions using any other name.
The object literal notation is not the same as the JavaScript Object Notation (JSON). Although they
look similar, there are differences between them:
JSON permits only property definition using "property": value syntax. The property name
must be double-quoted, and the definition cannot be a shorthand.
In JSON the values can only be strings, numbers, arrays, true, false, null, or another
(JSON) object.
A function value (see "Methods" above) can not be assigned to a value in JSON.
Objects like Date will be a string after JSON.parse().
JSON.parse() will reject computed property names and an error will be thrown.
RegExp
The RegExp constructor creates a regular expression object for matching text with a pattern.
For an introduction to regular expressions, read the Regular Expressions chapter in the JavaScript
Guide.
Constructor
/pattern/flags
new RegExp(pattern[, flags])
Parameters
pattern
Flags If specified, flags can have any combination of the following values:
ignore case
multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e.,
match the beginning or end of each line (delimited by \n or \r), not only the very beginning or
end of the whole input string)
Description
There are 2 ways to create a RegExp object: a literal notation and a constructor. To indicate strings,
the parameters to the literal notation do not use quotation marks while the parameters to the
constructor function do use quotation marks. So the following expressions create the same regular
expression:
/ab+c/i;
new RegExp('ab+c', 'i');
new RegExp(/ab+c/, 'i');
The literal notation provides compilation of the regular expression when the expression is evaluated.
Use literal notation when the regular expression will remain constant. For example, if you use literal
notation to construct a regular expression used in a loop, the regular expression won't be recompiled
on each iteration.
The constructor of the regular expression object, for example, new RegExp('ab+c'), provides
runtime compilation of the regular expression. Use the constructor function when you know the
regular expression pattern will be changing, or you don't know the pattern and are getting it from
another source, such as user input.
Starting with ECMAScript 6, new RegExp(/ab+c/, 'i') no longer throws a TypeError ("can't supply
flags when constructing one RegExp from another") when the first argument is a RegExp and the
second flags argument is present. A new RegExp from the arguments is created instead.
When using the constructor function, the normal string escape rules (preceding special characters
with \ when included in a string) are necessary. For example, the following are equivalent:
Character Classes
Character Sets
Boundaries
Grouping and back references
Quantifiers
Character Classes
Character Meaning
(The dot, the decimal point) matches any single character except line
terminators: \n, \r, \u2028 or \u2029.
Inside character class, the dot loses its special meaning and matches a literal
dot.
. Note that the m multiline flag doesn't change the dot behavior. So to match a
pattern across multiple lines, the character set [^] can be used (if you don't
mean an old version of IE, of course), it will match any character including
newlines.
For example, /.y/ matches "my" and "ay", but not "yes", in "yes make my
day".
Matches a digit character in the basic Latin alphabet. Equivalent to [0-9].
\d
For example, /\d/ or /[0-9]/ matches "2" in "B2 is the suite number".
Matches any character that is not a digit in the basic Latin alphabet.
\D Equivalent to [^0-9].
For example, /\D/ or /[^0-9]/ matches "B" in "B2 is the suite number".
For example, /\w/ matches "a" in "apple", "5" in "$5.28", and "3" in "3D".
Matches any character that is not a word character from the basic Latin
\W alphabet. Equivalent to [^A-Za-z0-9_].
\n Matches a linefeed.
\f Matches a form-feed.
\uhhhh Matches the character with the Unicode value hhhh (four hexadecimal digits).
For characters that are usually treated literally, indicates that the next
character is special and not to be interpreted literally.
For example, /b/ matches the character "b". By placing a backslash in front of
"b", that is by using /\b/, the character becomes special to mean match a
word boundary.
\ or
For characters that are usually treated specially, indicates that the next
character is not special and should be interpreted literally.
Character Meaning
A character set. Matches any one of the enclosed characters. You can
specify a range of characters by using a hyphen.
[xyz]
For example, [abcd] is the same as [a-d]. They match the "b" in "brisket" and
the "c" in "chop".
A negated or complemented character set. That is, it matches anything that is
[^xyz] not enclosed in the brackets. You can specify a range of characters by using
a hyphen.
Character Meaning
Matches either x or y.
x|y
For example, /green|red/ matches "green" in "green apple" and "red" in "red
apple".
Boundaries
Character Meaning
Matches beginning of input. If the multiline flag is set to true, also matches
immediately after a line break character.
^
For example, /^A/ does not match the "A" in "an A", but does match the first
"A" in "An A".
Matches end of input. If the multiline flag is set to true, also matches
$ immediately before a line break character.
For example, /t$/ does not match the "t" in "eater", but does match it in "eat".
Matches a zero-width word boundary, such as between a letter and a space.
(Not to be confused with [\b])
\b
For example, /\bno/ matches the "no" in "at noon"; /ly\b/ matches the "ly" in
"possibly yesterday".
Matches a zero-width non-word boundary, such as between two letters or
between two spaces.
\B
For example, /\Bon/ matches "on" in "at noon", and /ye\B/ matches "ye" in
"possibly yesterday".
Character Meaning
Matches x and remembers the match. These are called capturing groups.
The capturing groups are numbered according to the order of left parentheses
(x) of capturing groups, starting from 1. The matched substring can be recalled
from the resulting array's elements [1], ..., [n] or from the
predefined RegExp object's properties $1, ..., $9.
Capturing groups have a performance penalty. If you don't need the matched
substring to be recalled, prefer non-capturing parentheses (see below).
Where n is a positive integer. A back reference to the last substring matching
the n parenthetical in the regular expression (counting left parentheses).
\n
Quantifiers
Character Meaning
For example, /e?le?/ matches the "el" in "angel" and the "le" in "angle."
x?
If used immediately after any of the quantifiers *, +, ?, or {}, makes the
quantifier non-greedy (matching the minimum number of times), as opposed
to the default, which is greedy (matching the maximum number of times).
Where n is a positive integer. Matches exactly n occurrences of the preceding
item x.
x{n}
For example, /a{2}/ doesn't match the "a" in "candy", but it matches all of the
"a"'s in "caandy", and the first two "a"'s in "caaandy".
Where n is a positive integer. Matches at least n occurrences of the preceding
item x.
x{n,}
For example, /a{2,}/ doesn't match the "a" in "candy", but matches all of the
a's in "caandy" and in "caaaaaaandy".
Where n and m are positive integers. Matches at least n and at
most m occurrences of the preceding item x.
x{n,m} For example, /a{1,3}/ matches nothing in "cndy", the "a" in "candy", the two
"a"'s in "caandy", and the first three "a"'s in "caaaaaaandy". Notice that when
matching "caaaaaaandy", the match is "aaa", even though the original string
had more "a"'s in it.
Character Meaning
Properties
RegExp.prototype
RegExp.length
RegExp.lastIndex
Methods
The global RegExp object has no methods of its own, however, it does inherit some methods through
the prototype chain.
Properties
Methods
The following script uses the replace() method of the String instance to match a name in the
format first last and output it in the format last, first. In the replacement text, the script
uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular
expression pattern.
var re = /(\w+)\s(\w+)/;
var str = 'John Smith';
var newstr = str.replace(re, '$2, $1');
console.log(newstr);
The default line ending varies depending on the platform (Unix, Windows, etc.). The line splitting
provided in this example works on all platforms.
Note that the order of the patterns in the regular expression matters.
This example demonstrates how one could use the sticky flag on regular expressions to match
individual lines of multiline input.
One can test at run-time whether the sticky flag is supported, using try { … } catch { … }.
For this, either an eval(…) expression or the RegExp(regex-string, flags-string) syntax must
be used (since the /regex/flags notation is processed at compile-time, so throws an exception
before the catch block is encountered). For example:
var supports_sticky;
try { RegExp('', 'y'); supports_sticky = true; }
catch(e) { supports_sticky = false; }
console.log(supports_sticky); // logs 'true'
As mentioned above, \w or \W only matches ASCII based characters; for example, "a" to "z", "A" to
"Z", "0" to "9" and "_". To match characters from other languages such as Cyrillic or Hebrew,
use \uhhhh, where "hhhh" is the character's Unicode value in hexadecimal. This example
demonstrates how one can separate out Unicode characters from a word.
// and so on
Here's an external resource for getting the complete Unicode block range for different scripts:
Regexp-unicode-block.
Gecko-specific notes
Starting with Gecko 34 , in the case of a capturing group with quantifiers preventing its exercise, the
matched text for a capturing group is now undefined instead of an empty string:
// Firefox 33 or older
'x'.replace(/x(.)?/g, function(m, group) {
console.log("'group:" + group + "'");
}); // 'group:'
// Firefox 34 or newer
'x'.replace(/x(.)?/g, function(m, group) {
console.log("'group:" + group + "'");
}); // 'group:undefined'
Grouping
Syntax
( )
Description
Examples
Overriding multiplication and division first, then addition and subtraction to evaluate addition first.
var a = 1;
var b = 2;
var c = 3;
// default precedence
a + b * c // 7
// evaluated by default like this
a + (b * c) // 7
// which is equivalent to
a * c + b * c // 9
Property accessors provide access to an object's properties by using the dot notation or the bracket
notation.
Syntax
object.property
object["property"]
Description
One can think of an object as an associative array (a.k.a. map, dictionary, hash, lookup table).
The keys in this array are the names of the object's properties. It's typical when speaking of an
object's properties to make a distinction between properties and methods. However, the
property/method distinction is little more than a convention. A method is simply a property that can
be called, for example if it has a reference to a Function instance as its value.
There are two ways to access properties: dot notation and bracket notation.
Dot notation
get = object.property;
object.property = set;
In this code, property must be a valid JavaScript identifier, i.e. a sequence of alphanumerical
characters, also including the underscore ("_") and dollar sign ("$"), that cannot start with a number.
For example, object.$1 is valid, while object.1 is not.
document.createElement('pre');
Here, the method named "createElement" is retrieved from document and is called.
Bracket notation
get = object[property_name];
object[property_name] = set;
document['createElement']('pre');
Property names
Property names must be strings. This means that non-string objects cannot be used as keys in the
object. Any non-string object, including a number, is typecasted into a string via the toString method.
This also outputs "value", since both foo and bar are converted to the same string. In the
SpiderMonkey JavaScript engine, this string would be "['object Object']".
Method binding
A method is not bound to the object that it is a method of. Specifically, this is not fixed in a method,
i.e., this does not necessarily refer to an object containing the method. this is instead "passed" by
the function call. See method binding.
Note on eval
JavaScript novices often make the mistake of using eval where the bracket notation can be used
instead. For example, the following syntax is often seen in many scripts.
x = eval('document.forms.form_name.elements.' + strFormControl +
'.value');
x = document.forms["form_name"].elements[strFormControl].value;
new
The new operator creates an instance of a user-defined object type or of one of the built-in object
types that has a constructor function.
Syntax
new constructor[([arguments])]
Parameters
constructor
arguments
Description
To define an object type, create a function for the object type that specifies its name and properties.
An object can have a property that is itself another object. See the examples below.
When the code new Foo(...) is executed, the following things happen:
You can always add a property to a previously defined object. For example, the
statement car1.color = "black" adds a property color to car1, and assigns it a value of "black".
However, this does not affect any other objects. To add the new property to all objects of the same
type, you must add the property to the definition of the Car object type.
You can add a shared property to a previously defined object type by using
the Function.prototype property. This defines a property that is shared by all objects created with
that function, rather than by just one instance of the object type. The following code adds a color
property with value null to all objects of type car, and then overwrites that value with the string
"black" only in the instance object car1. For more information, see prototype.
function Car() {}
car1 = new Car();
console.log(car1.color); // undefined
Car.prototype.color = null;
console.log(car1.color); // null
car1.color = "black";
console.log(car1.color); // black
Examples
Suppose you want to create an object type for cars. You want this type of object to be called car,
and you want it to have properties for make, model, and year. To do this, you would write the
following function:
This statement creates mycar and assigns it the specified values for its properties. Then the value
of mycar.make is the string "Eagle", mycar.year is the integer 1993, and so on.
You can create any number of car objects by calls to new. For example:
Then you can rewrite the definition of car to include an owner property that takes a person object, as
follows:
Instead of passing a literal string or integer value when creating the new objects, the above
statements pass the objects rand and ken as the parameters for the owners. To find out the name of
the owner of car2, you can access the following property:
car2.owner.name
Arithmetic Operators
Arithmetic operators take numerical values (either literals or variables) as their operands and
return a single numerical value. The standard arithmetic operators are addition (+), subtraction (-),
multiplication (*), and division (/).
Addition (+)
The addition operator produces the sum of numeric operands or string concatenation.
Syntax
Operator: x + y
Examples
Subtraction (-)
The subtraction operator subtracts the two operands, producing their difference.
Syntax
Operator: x - y
Examples
5 - 3 // 2
3 - 5 // -2
"foo" - 3 // NaN
Division (/)
The division operator produces the quotient of its operands where the left operand is the dividend
and the right operand is the divisor.
Syntax
Operator: x / y
Examples
Multiplication (*)
Syntax
Operator: x * y
Examples
2 * 2 // 4
-2 * 2 // -4
Infinity * 0 // NaN
Infinity * Infinity // Infinity
"foo" * 2 // NaN
Remainder (%)
The remainder operator returns the remainder left over when one operand is divided by a second
operand. It always takes the sign of the dividend, not the divisor. It uses a built-in modulo function to
produce the result, which is the integer remainder of dividing var1 by var2 — for example
— var1 modulo var2. There is a proposal to get an actual modulo operator in a future version of
ECMAScript, the difference being that the modulo operator result would take the sign of the divisor,
not the dividend.
Syntax
12 % 5 // 2
-1 % 2 // -1
NaN % 2 // NaN
1 % 2 // 1
2 % 3 // 2
-4 % 2 // -0
5.5 % 2 // 1.5
Exponentiation (**)
The exponentiation operator returns the result of raising first operand to the power second operand.
that is, var1var2, in the preceding statement, where var1 and var2 are variables. Exponentiation
operator is right associative. a ** b ** c is equal to a ** (b ** c).
Syntax
Notes
In most languages like PHP and Python and others that have an exponentiation operator (typically ^
or **), the exponentiation operator is defined to have a higher precedence than unary operators such
as unary + and unary -, but there are a few exceptions. For example, in Bash or in the current ES7
exponentiation operator draft spec, the ** operator is defined to have a lower precedence than unary
operators.
Examples
2 ** 3 // 8
3 ** 2 // 9
3 ** 2.5 // 15.588457268119896
10 ** -1 // 0.1
NaN ** 2 // NaN
Increment (++)
The increment operator increments (adds one to) its operand and returns a value.
If used postfix, with operator after operand (for example, x++), then it returns the value
before incrementing.
If used prefix with operator before operand (for example, ++x), then it returns the value after
incrementing.
Syntax
Examples
// Postfix
var x = 3;
y = x++; // y = 3, x = 4
// Prefix
var a = 2;
b = ++a; // a = 3, b = 3
Decrement (--)
The decrement operator decrements (subtracts one from) its operand and returns a value.
If used postfix (for example, x--), then it returns the value before decrementing.
If used prefix (for example, --x), then it returns the value after decrementing.
Syntax
// Postfix
var x = 3;
y = x--; // y = 3, x = 2
// Prefix
var a = 2;
b = --a; // a = 1, b = 1
The unary negation operator precedes its operand and negates it.
Syntax
Operator: -x
Examples
var x = 3;
y = -x; // y = -3, x = 3
The unary plus operator precedes its operand and evaluates to its operand but attempts to converts
it into a number, if it isn't already. Although unary negation (-) also can convert non-numbers, unary
plus is the fastest and preferred way of converting something into a number, because it does not
perform any other operations on the number. It can convert string representations of integers and
floats, as well as the non-string values true, false, and null. Integers in both decimal and
hexadecimal ("0x"-prefixed) formats are supported. Negative numbers are supported (though not for
hex). If it cannot parse a particular value, it will evaluate to NaN.
Syntax
Operator: +x
+3 // 3
+"3" // 3
+true // 1
+false // 0
+null // 0
delete
Syntax
delete expression
delete object.property
delete object['property']
Parameters
object
property
Return value
Throws in strict mode if the property is an own non-configurable property (returns false in non-
strict). Returns true in all other cases.
Unlike what common belief suggests, the delete operator has nothing to do with directly freeing
memory (it only does indirectly via breaking references. See the memory management page for
more details).
If the delete operator succeeds, it removes the property from the object entirely. However, if a
property with the same name exists on the object's prototype chain, the object will inherit that
property from the prototype.
delete is only effective on an object's properties. It has no effect on variable or function names.
While sometimes mis-characterized as global variables, assignments that don't specify an object
(e.g. x = 5) are actually property assignments on the global object.
delete can't remove certain properties of predefined objects (like Object, Array, Math etc). These
are described in ECMAScript 5 and later as non-configurable.
The "temporal dead zone" (TDZ), specified in ECMAScript 6 for const and let declarations, also
applies to the delete operator. Thus, code like the following will throw a ReferenceError.
function foo() {
delete x;
let x;
}
function bar() {
delete y;
const y;
}
Examples
x = 42; // creates the property x on the global object
var y = 43; // creates the property y on the global object, and marks
it as non-configurable
myobj = {
function f() {
var z = 44;
If the object inherits a property from a prototype, and doesn't have the property itself, the property
can't be deleted by referencing the object. You can, however, delete it directly on the prototype.
function Foo(){}
Foo.prototype.bar = 42;
var foo = new Foo();
When you delete an array element, the array length is not affected. This holds even if you delete the
last element of the array.
When the delete operator removes an array element, that element is no longer in the array. In the
following example, trees[3] is removed with delete.
If you want an array element to exist but have an undefined value, use the undefined value instead
of the delete operator. In the following example, trees[3] is assigned the value undefined, but the
array element still exists:
void
The void operator evaluates the given expression and then returns undefined.
Description
This operator allows inserting expressions that produce side effects into places where an expression
that evaluates to undefined is desired.
The void operator is often used merely to obtain the undefined primitive value, usually using
"void(0)" (which is equivalent to "void 0"). In these cases, the global variable undefined can be
used instead (assuming it has not been assigned to a non-default value).
foo();
biz();
}();
JavaScript URIs
When a browser follows a javascript: URI, it evaluates the code in the URI and then replaces the
contents of the page with the returned value, unless the returned value is undefined.
The void operator can be used to return undefined. For example:
<a href="javascript:void(0);">
<a href="javascript:void(document.body.style.backgroundColor='green');">
Click here for green background
</a>
Note, however, that the javascript: pseudo protocol is discouraged over other alternatives, such
as unobtrusive event handlers.
typeof
The typeof operator returns a string indicating the type of the unevaluated operand.
Syntax
typeof operand
Parameters
Description
The following table summarizes the possible return values of typeof. For more information about
types and primitives, see also the JavaScript data structure page.
Examples
// Numbers
typeof 37 === 'number';
typeof 3.14 === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; // Despite being "Not-A-Number"
typeof Number(1) === 'number'; // but never use this form!
// Booleans
typeof true === 'boolean';
typeof false === 'boolean';
typeof Boolean(true) === 'boolean'; // but never use this form!
// Symbols
typeof Symbol() === 'symbol'
typeof Symbol('foo') === 'symbol'
typeof Symbol.iterator === 'symbol'
// Undefined
typeof undefined === 'undefined';
typeof blabla === 'undefined'; // an undefined variable
// Objects
typeof {a:1} === 'object';
// Functions
null
In the first implementation of JavaScript, JavaScript values were represented as a type tag and a
value. The type tag for objects was 0. null was represented as the NULL pointer (0x00 in most
platforms). Consequently, null had 0 as type tag, hence the bogus typeof return value. (reference)
A fix was proposed for ECMAScript (via an opt-in), but was rejected. It would have resulted
in typeof null === 'null'.
Regular expressions
IE-specific notes
On IE 6, 7, and 8 a lot of host objects are objects and not functions. For example:
Logical Operators
Logical operators are typically used with Boolean (logical) values. When they are, they return a
Boolean value. However, the && and || operators actually return the value of one of the specified
operands, so if these operators are used with non-Boolean values, they may return a non-Boolean
value.
Examples of expressions that can be converted to false are those that evaluate to null, 0, the empty
string (""), or undefined.
Even though the && and || operators can be used with operands that are not Boolean values, they
can still be considered Boolean operators since their return values can always be converted to
Boolean values.
Short-Circuit Evaluation
As logical expressions are evaluated left to right, they are tested for possible "short-circuit"
evaluation using the following rules:
The rules of logic guarantee that these evaluations are always correct. Note that the anything part of
the above expressions is not evaluated, so any side effects of doing so do not take effect. Also note
that the anything part of the above expression is any single logical expression (as indicated by the
parentheses).
function shortCircuitEvaluation() {
doSomething() || doSomethingElse()
}
function equivalentEvaluation() {
var flag = doSomething();
if (!flag) {
doSomethingElse();
}
}
However, the following expressions are not equivalent due to operator precedence, and stresses the
importance of requiring the right hand operator to be a single expression (grouped if needed by
parentheses).
The following code shows examples of the && (logical AND) operator.
Logical OR (||)
Conversion rules
Converting AND to OR
!(!bCondition1 || !bCondition2)
Converting OR to AND
bCondition1 || bCondition2
!!bCondition
bCondition
As logical expressions are evaluated left to right, it is always possible to remove parentheses from a
complex expression following some rules.
Removing nested OR
Bitwise Operators
Bitwise operators treat their operands as a sequence of 32 bits (zeroes and ones), rather than as
decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary
The operands of all bitwise operators are converted to signed 32-bit integers in two's complement
format. Two's complement format means that a number's negative counterpart (e.g. 5 vs. -5) is all
the number's bits inverted (bitwise NOT of the number, a.k.a. ones' complement of the number) plus
one. For example, the following encodes the integer 314:
00000000000000000000000100111010
11111111111111111111111011000101
Finally, the following encodes -314, i.e. the two's complement of 314:
11111111111111111111111011000110
The two's complement guarantees that the left-most bit is 0 when the number is positive and 1 when
the number is negative. Thus, it is called the sign bit.
The numbers -2147483648 and 2147483647 are the minimum and the maximum integers
representable through a 32bit signed number.
The operands are converted to 32-bit integers and expressed by a series of bits (zeroes and
ones).
Each bit in the first operand is paired with the corresponding bit in the second operand: first
bit to first bit, second bit to second bit, and so on.
The operator is applied to each pair of bits, and the result is constructed bitwise.
Performs the AND operation on each pair of bits. a AND b yields 1 only if both a and b are 1. The
truth table for the AND operation is:
Bitwise ANDing any number x with 0 yields 0. Bitwise ANDing any number x with -1 yields x.
| (Bitwise OR)
Performs the OR operation on each pair of bits. a OR b yields 1 if either a or b is 1. The truth table
for the OR operation is:
Bitwise ORing any number x with 0 yields x. Bitwise ORing any number x with -1 yields -1.
^ (Bitwise XOR)
Performs the XOR operation on each pair of bits. a XOR b yields 1 if a and b are different. The truth
table for the XOR operation is:
Bitwise XORing any number x with 0 yields x. Bitwise XORing any number x with -1 yields ~x.
~ (Bitwise NOT)
Performs the NOT operator on each bit. NOT a yields the inverted value (a.k.a. one's complement)
of a. The truth table for the NOT operation is:
Bitwise NOTing any number x yields -(x + 1). For example, ~5 yields -6.
The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second
specifies the number of bit positions by which the first operand is to be shifted. The direction of the
shift operation is controlled by the operator used.
Shift operators convert their operands to 32-bit integers in big-endian order and return a result of the
same type as the left operand. The right operand should be less than 32, but if not only the low five
bits will be used.
This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to
the left are discarded. Zero bits are shifted in from the right.
This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off
to the right are discarded. Copies of the leftmost bit are shifted in from the left. Since the new
leftmost bit has the same value as the previous leftmost bit, the sign bit (the leftmost bit) does not
change. Hence the name "sign-propagating".
This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off
to the right are discarded. Zero bits are shifted in from the left. The sign bit becomes 0, so the result
is always non-negative.
For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result.
For example, 9 >>> 2 yields 2, the same as 9 >> 2:
However, this is not the case for negative numbers. For example, -9 >>> 2 yields 1073741821,
which is different than -9 >> 2 (which yields -3):
Examples
These flags are represented by a sequence of bits: DCBA. When a flag is set, it has a value of 1.
When a flag is cleared, it has a value of 0. Suppose a variable flags has the binary value 0101:
Since bitwise operators are 32-bit, 0101 is actually 00000000000000000000000000000101, but the
preceding zeroes can be neglected since they contain no meaningful information.
A bitmask is a sequence of bits that can manipulate and/or read flags. Typically, a "primitive" bitmask
for each flag is defined:
New bitmasks can be created by using the bitwise logical operators on these primitive bitmasks. For
example, the bitmask 1011 can be created by ORing FLAG_A, FLAG_B, and FLAG_D:
var mask = FLAG_A | FLAG_B | FLAG_D; // 0001 | 0010 | 1000 => 1011
// if we own a cat
if (flags & FLAG_C) { // 0101 & 0100 => 0100 => true
// do stuff
}
A bitmask with multiple set flags acts like an "either/or". For example, the following two are
equivalent:
Flags can be set by ORing them with a bitmask, where each bit with the value one will set the
corresponding flag, if that flag isn't already set. For example, the bitmask 1100 can be used to set
flags C and D:
Flags can be cleared by ANDing them with a bitmask, where each bit with the value zero will clear
the corresponding flag, if it isn't already cleared. This bitmask can be created by NOTing primitive
bitmasks. For example, the bitmask 1010 can be used to clear flags A and C:
The mask could also have been created with ~FLAG_A & ~FLAG_C (De Morgan's law):
Flags can be toggled by XORing them with a bitmask, where each bit with the value one will toggle
the corresponding flag. For example, the bitmask 0110 can be used to toggle flags B and C:
Finally, the flags can all be flipped with the NOT operator:
Conversion snippets
function createMask () {
var nMask = 0, nFlag = 0, nLen = arguments.length > 32 ? 32 :
arguments.length;
for (nFlag; nFlag < nLen; nMask |= arguments[nFlag] << nFlag++);
return nMask;
}
var mask1 = createMask(true, true, false, true); // 11, i.e.: 1011
var mask2 = createMask(false, false, true); // 4, i.e.: 0100
var mask3 = createMask(true); // 1, i.e.: 0001
// etc.
If you want to create an Array of Booleans from a mask you can use this code:
alert(nResult); // 19
For didactic purpose only (since there is the Number.toString(2) method), we show how it is
possible to modify the arrayFromMask algorithm in order to create a String containing the binary
representation of a Number, rather than an Array of Booleans:
Conditional Operator
The conditional (ternary) operator is the only JavaScript operator that takes three operands. This
operator is frequently used as a shortcut for the if statement.
Syntax
condition ? expr1 : expr2
Parameters
condition
expr1, expr2
If condition is true, the operator returns the value of expr1; otherwise, it returns the value of expr2.
For example, to display a different message based on the value of the isMember variable, you could
use this statement:
Multiple ternary evaluations are also possible (note: the conditional operator is right associative):
You can also use ternary evaluations in free space in order to do different operations:
You can also do more than one single operation per case, separating them with a comma:
age > 18 ? (
alert("OK, you can go."),
location.assign("continue.html")
) : (
stop = true,
alert("Sorry, you are much too young!")
);
location.assign(url); // "stop.html"
Assignment Operators
An assignment operator assigns a value to its left operand based on the value of its right operand.
Overview
The basic assignment operator is equal (=), which assigns the value of its right operand to its left
operand. That is, x = y assigns the value of y to x. The other assignment operators are usually
shorthand for standard operations, as shown in the following definitions and examples.
Assignment
Simple assignment operator which assigns a value to a variable. Chaining the assignment operator
is possible in order to assign a single value to multiple variables. See the example.
Syntax
Operator: x = y
x = y // x is 10
x = y = z // x, y and z are all 25
Addition assignment
The addition assignment operator adds the value of the right operand to a variable and assigns the
result to the variable. The types of the two operands determine the behavior of the addition
assignment operator. Addition or concatenation is possible. See the addition operator for more
details.
Syntax
Operator: x += y
Meaning: x = x + y
Examples
Subtraction assignment
The subtraction assignment operator subtracts the value of the right operand from a variable and
assigns the result to the variable. See the subtraction operator for more details.
Syntax
Operator: x -= y
Meaning: x = x - y
Examples
// Assuming the following variable
// bar = 5
bar -= 2 // 3
bar -= "foo" // NaN
Multiplication assignment
The multiplication assignment operator multiplies a variable by the value of the right operand and
assigns the result to the variable. See the multiplication operator for more details.
Syntax
Operator: x *= y
Meaning: x = x * y
Examples
DroidScript - Languaje Page 129
// Assuming the following variable
// bar = 5
bar *= 2 // 10
bar *= "foo" // NaN
Division assignment
The division assignment operator divides a variable by the value of the right operand and assigns
the result to the variable. See the division operator for more details.
Syntax
Operator: x /= y
Meaning: x = x / y
Examples
bar /= 2 // 2.5
bar /= "foo" // NaN
bar /= 0 // Infinity
Remainder assignment
The remainder assignment operator divides a variable by the value of the right operand and assigns
the remainder to the variable. See the remainder operator for more details.
Syntax
Operator: x %= y
Meaning: x = x % y
Examples
bar %= 2 // 1
bar %= "foo" // NaN
bar %= 0 // NaN
Exponentiation assignment
The exponentiation assignment operator returns the result of raising first operand to
the power second operand. See the exponentiation operator for more details.
Syntax
Operator: x **= y
Meaning: x = x ** y
Examples
bar **= 2 // 25
bar **= "foo" // NaN
The left shift assignment operator moves the specified amount of bits to the left and assigns the
result to the variable. See the left shift operator for more details.
Syntax
Operator: x <<= y
Meaning: x = x << y
Examples
The right shift assignment operator moves the specified amount of bits to the right and assigns the
result to the variable. See the right shift operator for more details.
Syntax
Operator: x >>= y
Meaning: x = x >> y
Examples
The unsigned right shift assignment operator moves the specified amount of bits to the right and
assigns the result to the variable. See the unsigned right shift operator for more details.
Syntax
Operator: x >>>= y
Meaning: x = x >>> y
Examples
The bitwise AND assignment operator uses the binary representation of both operands, does a
bitwise AND operation on them and assigns the result to the variable. See the bitwise AND
operator for more details.
Syntax
Operator: x &= y
Meaning: x = x & y
Example
var bar = 5;
// 5: 00000000000000000000000000000101
// 2: 00000000000000000000000000000010
bar &= 2; // 0
The bitwise XOR assignment operator uses the binary representation of both operands, does a
bitwise XOR operation on them and assigns the result to the variable. See the bitwise XOR
operator for more details.
Syntax
Operator: x ^= y
Meaning: x = x ^ y
Example
var bar = 5;
bar ^= 2; // 7
// 5: 00000000000000000000000000000101
// 2: 00000000000000000000000000000010
Bitwise OR assignment
The bitwise OR assignment operator uses the binary representation of both operands, does a
bitwise OR operation on them and assigns the result to the variable. See the bitwise OR
operator for more details.
Syntax
Operator: x |= y
Meaning: x = x | y
Example
var bar = 5;
bar |= 2; // 7
// 5: 00000000000000000000000000000101
// 2: 00000000000000000000000000000010
// -----------------------------------
// 7: 00000000000000000000000000000111
Examples
In unusual situations, the assignment operator (e.g. x += y) is not identical to the meaning
expression (here x = x + y). When the left operand of an assignment operator itself contains an
assignment operator, the left operand is evaluated only once. For example:
Comma Operator
The comma operator evaluates each of its operands (from left to right) and returns the value of the
last operand.
Parameters
expr1, expr2, expr3...
Any expressions.
Description
You can use the comma operator when you want to include multiple expressions in a location that
requires a single expression. The most common usage of this operator is to supply multiple
parameters in a for loop.
Example
If a is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator
to increment two variables at once. Note that the comma in the var statement is not the comma
operator, because it doesn't exist within an expression. Rather, it is a special character
in var statements to combine multiple of them into one. Practically, that comma behaves almost the
same as the comma operator, though. The code prints the values of the diagonal elements in the
array:
Another example that one could make with comma operator is processing before returning. As
stated, only the last element will be returned but all others are going to be evaluated as well. So, one
could do:
function myFunc () {
var x = 0;