Pages

What is JavaScript

JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions. While it is most well-known as the scripting language for Web pages, many non-browser environments also use it, such as Node.js, Apache CouchDB and Adobe Acrobat. JavaScript is a prototype-based, multi-paradigm, single-threaded, dynamic language, supporting object-oriented, imperative, and declarative (e.g. functional programming) styles. Read more about JavaScript.

JavaScript ("JS" for short) is a full-fledged dynamic programming language that, when applied to an HTML document, can provide dynamic interactivity on websites. It was invented by Brendan Eich, co-founder of the Mozilla project, the Mozilla Foundation, and the Mozilla Corporation.
JavaScript is incredibly versatile and beginner friendly. With more experience, you'll be able to create games, animated 2D and 3D graphics, comprehensive database-driven apps, and much more!

History of JavaScript:

The standard for JavaScript is ECMAScript. As of 2012, all modern browsers fully support ECMAScript 5.1. Older browsers support at least ECMAScript 3. On June 17, 2015, ECMA International published the sixth major version of ECMAScript, which is officially called ECMAScript 2015, and was initially referred to as ECMAScript 6 or ES6. Since then, ECMAScript standards are on yearly release cycles. This documentation refers to the latest draft version, which is currently ECMAScript 2020.

Operators
JavaScript has the following types of operators. This section describes the operators and contains information about operator precedence.
JavaScript has both binary and unary operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the operator and one after the operator:
operand1 operator operand2
For example, 3+4 or x*y.
A unary operator requires a single operand, either before or after the operator:
operator operand
or
operand operator
For example, x++ or ++x.

Assignment operators

An assignment operator assigns a value to its left operand based on the value of its right operand. The simple 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.
There are also compound assignment operators that are shorthand for the operations listed in the following table:
Compound assignment operators
NameShorthand operatorMeaning
Assignmentx = yx = y
Addition assignmentx += yx = x + y
Subtraction assignmentx -= yx = x - y
Multiplication assignmentx *= yx = x * y
Division assignmentx /= yx = x / y
Remainder assignmentx %= yx = x % y
Exponentiation assignmentx **= yx = x ** y
Left shift assignmentx <<= yx = x << y
Right shift assignmentx >>= yx = x >> y
Unsigned right shift assignmentx >>>= yx = x >>> y
Bitwise AND assignmentx &= yx = x & y
Bitwise XOR assignmentx ^= yx = x ^ y
Bitwise OR assignmentx |= yx = x | y

Destructuring

For more complex assignments, the destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.
var foo = ['one', 'two', 'three'];

// without destructuring
var one   = foo[0];
var two   = foo[1];
var three = foo[2];

// with destructuring
var [one, two, three] = foo;

Comparison operators

comparison operator compares its operands and returns a logical value based on whether the comparison is true. The operands can be numerical, string, logical, or object values. Strings are compared based on standard lexicographical ordering, using Unicode values. In most cases, if the two operands are not of the same type, JavaScript attempts to convert them to an appropriate type for the comparison. This behavior generally results in comparing the operands numerically. The sole exceptions to type conversion within comparisons involve the === and !== operators, which perform strict equality and inequality comparisons. These operators do not attempt to convert the operands to compatible types before checking equality. The following table describes the comparison operators in terms of this sample code:
var var1 = 3;
var var2 = 4;
Comparison operators
OperatorDescriptionExamples returning true
Equal (==)Returns true if the operands are equal.3 == var1
"3" == var1
3 == '3'
Not equal (!=)Returns true if the operands are not equal.var1 != 4
var2 != "3"
Strict equal (===)Returns true if the operands are equal and of the same type. See also Object.is and sameness in JS.3 === var1
Strict not equal (!==)Returns true if the operands are of the same type but not equal, or are of different type.var1 !== "3"
3 !== '3'
Greater than (>)Returns true if the left operand is greater than the right operand.var2 > var1
"12" > 2
Greater than or equal (>=)Returns true if the left operand is greater than or equal to the right operand.var2 >= var1
var1 >= 3
Less than (<)Returns true if the left operand is less than the right operand.var1 < var2
"2" < 12
Less than or equal (<=)Returns true if the left operand is less than or equal to the right operand.var1 <= var2
var2 <= 5
Note: (=>) is not an operator, but the notation for Arrow functions.

Arithmetic operators

An arithmetic operator takes numerical values (either literals or variables) as their operands and returns a single numerical value. The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/). These operators work as they do in most other programming languages when used with floating point numbers (in particular, note that division by zero produces Infinity). For example:
1 / 2; // 0.5
1 / 2 == 1.0 / 2.0; // this is true
In addition to the standard arithmetic operations (+, -, * /), JavaScript provides the arithmetic operators listed in the following table:
Arithmetic operators
OperatorDescriptionExample
Remainder (%)Binary operator. Returns the integer remainder of dividing the two operands.12 % 5 returns 2.
Increment (++)Unary operator. Adds one to its operand. If used as a prefix operator (++x), returns the value of its operand after adding one; if used as a postfix operator (x++), returns the value of its operand before adding one.If x is 3, then ++x sets x to 4 and returns 4, whereas x++ returns 3 and, only then, sets x to 4.
Decrement (--)Unary operator. Subtracts one from its operand. The return value is analogous to that for the increment operator.If x is 3, then --x sets x to 2 and returns 2, whereas x-- returns 3 and, only then, sets x to 2.
Unary negation (-)Unary operator. Returns the negation of its operand.If x is 3, then -x returns -3.
Unary plus (+)Unary operator. Attempts to convert the operand to a number, if it is not already.+"3" returns 3.
+true returns 1.
Exponentiation operator (**)Calculates the base to the exponent power, that is, baseexponent2 ** 3 returns 8.
10 ** -1 returns 0.1.

Bitwise operators

bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.
The following table summarizes JavaScript's bitwise operators.
Bitwise operators
OperatorUsageDescription
Bitwise ANDa & bReturns a one in each bit position for which the corresponding bits of both operands are ones.
Bitwise ORa | bReturns a zero in each bit position for which the corresponding bits of both operands are zeros.
Bitwise XORa ^ bReturns a zero in each bit position for which the corresponding bits are the same.
[Returns a one in each bit position for which the corresponding bits are different.]
Bitwise NOT~ aInverts the bits of its operand.
Left shifta << bShifts a in binary representation b bits to the left, shifting in zeros from the right.
Sign-propagating right shifta >> bShifts a in binary representation b bits to the right, discarding bits shifted off.
Zero-fill right shifta >>> bShifts a in binary representation b bits to the right, discarding bits shifted off, and shifting in zeros from the left.

Bitwise logical operators

Conceptually, the bitwise logical operators work as follows:
  • The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones). Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32 bit integer:
    Before: 11100110111110100000000000000110000000000001
    After:              10100000000000000110000000000001
  • 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.
For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111. So, when the bitwise operators are applied to these values, the results are as follows:
Bitwise operator examples
ExpressionResultBinary Description
15 & 991111 & 1001 = 1001
15 | 9151111 | 1001 = 1111
15 ^ 961111 ^ 1001 = 0110
~15-16~00000000...00001111 = 11111111...11110000
~9-10~00000000...00001001 = 11111111...11110110
Note that all 32 bits are inverted using the Bitwise NOT operator, and that values with the most significant (left-most) bit set to 1 represent negative numbers (two's-complement representation). ~x evaluates to the same value that -x - 1 evaluates to.

Bitwise shift operators

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 thirty-two-bit integers and return a result of the same type as the left operand.
The shift operators are listed in the following table.
Bitwise shift operators
OperatorDescriptionExample
Left shift
(<<)
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.9<<2 yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36.
Sign-propagating right shift (>>)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.9>>2 yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2. Likewise, -9>>2 yields -3, because the sign is preserved.
Zero-fill right shift (>>>)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.19>>>2 yields 4, because 10011 shifted 2 bits to the right becomes 100, which is 4. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result.

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. The logical operators are described in the following table.
Logical operators
OperatorUsageDescription
Logical AND (&&)expr1 && expr2Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
Logical OR (||)expr1 || expr2Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.
Logical NOT (!)!exprReturns false if its single operand that can be converted to true; otherwise, returns true.
Examples of expressions that can be converted to false are those that evaluate to null, 0, NaN, the empty string (""), or undefined.
The following code shows examples of the && (logical AND) operator.
var a1 =  true && true;     // t && t returns true
var a2 =  true && false;    // t && f returns false
var a3 = false && true;     // f && t returns false
var a4 = false && (3 == 4); // f && f returns false
var a5 = 'Cat' && 'Dog';    // t && t returns Dog
var a6 = false && 'Cat';    // f && t returns false
var a7 = 'Cat' && false;    // t && f returns false
The following code shows examples of the || (logical OR) operator.
var o1 =  true || true;     // t || t returns true
var o2 = false || true;     // f || t returns true
var o3 =  true || false;    // t || f returns true
var o4 = false || (3 == 4); // f || f returns false
var o5 = 'Cat' || 'Dog';    // t || t returns Cat
var o6 = false || 'Cat';    // f || t returns Cat
var o7 = 'Cat' || false;    // t || f returns Cat
The following code shows examples of the ! (logical NOT) operator.
var n1 = !true;  // !t returns false
var n2 = !false; // !f returns true
var n3 = !'Cat'; // !t returns false

Short-circuit evaluation

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:
  • false && anything is short-circuit evaluated to false.
  • true || anything is short-circuit evaluated to true.
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.
Note that for the second case, in modern code you can use the new Nullish coalescing operator (??) that works like ||, but it only returns the second expression, when the first one is "nullish", i.e. null or undefined. It is thus the better alternative to provide defaults, when values like '' or 0 are valid values for the first expression, too.

String operators

In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.
For example,
console.log('my ' + 'string'); // console logs the string "my string".
The shorthand assignment operator += can also be used to concatenate strings.
For example,
var mystring = 'alpha';
mystring += 'bet'; // evaluates to "alphabet" and assigns this value to mystring.

Conditional (ternary) operator

The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two values based on a condition. The syntax is:
condition ? val1 : val2
If condition is true, the operator has the value of val1. Otherwise it has the value of val2. You can use the conditional operator anywhere you would use a standard operator.
For example,
var status = (age >= 18) ? 'adult' : 'minor';
This statement assigns the value "adult" to the variable status if age is eighteen or more. Otherwise, it assigns the value "minor" to status.

Comma operator

The comma operator (,) simply evaluates both of its operands and returns the value of the last operand. This operator is primarily used inside a for loop, to allow multiple variables to be updated each time through the loop.
For example, if a is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to update two variables at once. The code prints the values of the diagonal elements in the array:
var x = [0,1,2,3,4,5,6,7,8,9]
var a = [x, x, x, x, x];

for (var i = 0, j = 9; i <= j; i++, j--)
  console.log('a[' + i + '][' + j + ']= ' + a[i][j]);

Unary operators

A unary operation is an operation with only one operand.

delete

The delete operator deletes an object, an object's property, or an element at a specified index in an array. The syntax is:
delete objectName;
delete objectName.property;
delete objectName[index];
delete property; // legal only within a with statement
where objectName is the name of an object, property is an existing property, and index is an integer representing the location of an element in an array.
The fourth form is legal only within a with statement, to delete a property from an object.
You can use the delete operator to delete variables declared implicitly but not those declared with the var statement.
If the delete operator succeeds, it sets the property or element to undefined. The delete operator returns true if the operation is possible; it returns false if the operation is not possible.
x = 42;
var y = 43;
myobj = new Number();
myobj.h = 4;    // create property h
delete x;       // returns true (can delete if declared implicitly)
delete y;       // returns false (cannot delete if declared with var)
delete Math.PI; // returns false (cannot delete predefined properties)
delete myobj.h; // returns true (can delete user-defined properties)
delete myobj;   // returns true (can delete if declared implicitly)
Deleting array elements
When you delete an array element, the array length is not affected. For example, if you delete a[3]a[4] is still a[4] and a[3] is undefined.
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. However, trees[3] is still addressable and returns undefined.
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
delete trees[3];
if (3 in trees) {
  // this does not get executed
}
If you want an array element to exist but have an undefined value, use the undefined keyword instead of the delete operator. In the following example, trees[3] is assigned the value undefined, but the array element still exists:
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
trees[3] = undefined;
if (3 in trees) {
  // this gets executed
}

typeof

The typeof operator is used in either of the following ways:
typeof operand
typeof (operand)
The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.
Suppose you define the following variables:
var myFun = new Function('5 + 2');
var shape = 'round';
var size = 1;
var foo = ['Apple', 'Mango', 'Orange'];
var today = new Date();
The typeof operator returns the following results for these variables:
typeof myFun;       // returns "function"
typeof shape;       // returns "string"
typeof size;        // returns "number"
typeof foo;         // returns "object"
typeof today;       // returns "object"
typeof doesntExist; // returns "undefined"
For the keywords true and null, the typeof operator returns the following results:
typeof true; // returns "boolean"
typeof null; // returns "object"
For a number or string, the typeof operator returns the following results:
typeof 62;            // returns "number"
typeof 'Hello world'; // returns "string"
For property values, the typeof operator returns the type of value the property contains:
typeof document.lastModified; // returns "string"
typeof window.length;         // returns "number"
typeof Math.LN2;              // returns "number"
For methods and functions, the typeof operator returns results as follows:
typeof blur;        // returns "function"
typeof eval;        // returns "function"
typeof parseInt;    // returns "function"
typeof shape.split; // returns "function"
For predefined objects, the typeof operator returns results as follows:
typeof Date;     // returns "function"
typeof Function; // returns "function"
typeof Math;     // returns "object"
typeof Option;   // returns "function"
typeof String;   // returns "function"

void

The void operator is used in either of the following ways:
void (expression)
void expression
The void operator specifies an expression to be evaluated without returning a value. expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them.
You can use the void operator to specify an expression as a hypertext link. The expression is evaluated but is not loaded in place of the current document.
The following code creates a hypertext link that does nothing when the user clicks it. When the user clicks the link, void(0) evaluates to undefined, which has no effect in JavaScript.
<a href="javascript:void(0)">Click here to do nothing</a>
The following code creates a hypertext link that submits a form when the user clicks it.
<a href="javascript:void(document.form.submit())">
Click here to submit</a>

Relational operators

A relational operator compares its operands and returns a Boolean value based on whether the comparison is true.

in

The in operator returns true if the specified property is in the specified object. The syntax is:
propNameOrNumber in objectName
where propNameOrNumber is a string, numeric, or symbol expression representing a property name or array index, and objectName is the name of an object.
The following examples show some uses of the in operator.
// Arrays
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
0 in trees;        // returns true
3 in trees;        // returns true
6 in trees;        // returns false
'bay' in trees;    // returns false (you must specify the index number,
                   // not the value at that index)
'length' in trees; // returns true (length is an Array property)

// built-in objects
'PI' in Math;          // returns true
var myString = new String('coral');
'length' in myString;  // returns true

// Custom objects
var mycar = { make: 'Honda', model: 'Accord', year: 1998 };
'make' in mycar;  // returns true
'model' in mycar; // returns true

instanceof

The instanceof operator returns true if the specified object is of the specified object type. The syntax is:
objectName instanceof objectType
where objectName is the name of the object to compare to objectType, and objectType is an object type, such as Date or Array.
Use instanceof when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.
For example, the following code uses instanceof to determine whether theDay is a Date object. Because theDay is a Date object, the statements in the if statement execute.
var theDay = new Date(1995, 12, 17);
if (theDay instanceof Date) {
  // statements to execute
}

Operator precedence

The precedence of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses.
The following table describes the precedence of operators, from highest to lowest.
Operator precedence
Operator typeIndividual operators
member. []
call / create instance() new
negation/increment! ~ - + ++ -- typeof void delete
multiply/divide* / %
addition/subtraction+ -
bitwise shift<< >> >>>
relational< <= > >= in instanceof
equality== != === !==
bitwise-and&
bitwise-xor^
bitwise-or|
logical-and&&
logical-or||
conditional?:
assignment= += -= *= /= %= <<= >>= >>>= &= ^= |=
comma,
A more detailed version of this table, complete with links to additional details about each operator, may be found in JavaScript Reference.

Expressions

An expression is any valid unit of code that resolves to a value.
Every syntactically valid expression resolves to some value but conceptually, there are two types of expressions: with side effects (for example: those that assign value to a variable) and those that in some sense evaluate and therefore resolve to a value.
The expression x = 7 is an example of the first type. This expression uses the = operator to assign the value seven to the variable x. The expression itself evaluates to seven.
The code 3 + 4 is an example of the second expression type. This expression uses the + operator to add three and four together without assigning the result, seven, to a variable.

JavaScript has the following expression categories:
  • Arithmetic: evaluates to a number, for example 3.14159. (Generally uses arithmetic operators.)
  • String: evaluates to a character string, for example, "Fred" or "234". (Generally uses string operators.)
  • Logical: evaluates to true or false. (Often involves logical operators.)
  • Primary expressions: Basic keywords and general expressions in JavaScript.
  • Left-hand-side expressions: Left values are the destination of an assignment.

Primary expressions

Basic keywords and general expressions in JavaScript.

this

Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this either with the dot or the bracket notation:
this['propertyName']
this.propertyName
Suppose a function called validate validates an object's value property, given the object and the high and low values:
function validate(obj, lowval, hival) {
  if ((obj.value < lowval) || (obj.value > hival))
    console.log('Invalid Value!');
}
You could call validate in each form element's onChange event handler, using this to pass it to the form element, as in the following example:
<p>Enter a number between 18 and 99:</p>
<input type="text" name="age" size=3 onChange="validate(this, 18, 99);">

Grouping operator

The grouping operator ( ) controls the precedence of evaluation in expressions. For example, you can override 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

// now overriding precedence 
// addition before multiplication   
(a + b) * c   // 9

// which is equivalent to
a * c + b * c // 9

Left-hand-side expressions

Left values are the destination of an assignment.

new

You can use the new operator to create an instance of a user-defined object type or of one of the built-in object types. Use new as follows:
var objectName = new objectType([param1, param2, ..., paramN]);

super

The super keyword is used to call functions on an object's parent. It is useful with classes to call the parent constructor, for example.
super([arguments]); // calls the parent constructor.
super.functionOnParent([arguments]);

Spread operator

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
Example: Today if you have an array and want to create a new array with the existing one being part of it, the array literal syntax is no longer sufficient and you have to fall back to imperative code, using a combination of pushspliceconcat, etc. With spread syntax this becomes much more succinct:
var parts = ['shoulders', 'knees'];
var lyrics = ['head', ...parts, 'and', 'toes'];
Similarly, the spread operator works with function calls:

function f(x, y, z) { }
var args = [0, 1, 2];
f(...args);

The difference between var and let?

1)For a start, if you write a multiline JavaScript program that declares and initializes a variable, you can actually declare a variable with var after you initialize it and it will still work. For example:
myName = 'Chris';

function logName() {
  console.log(myName);
}

logName();

var myName;
This works because of hoisting — read var hoisting for more detail on the subject.
Hoisting no longer works with let. If we changed var to let in the above example, it would fail with an error. This is a good thing — declaring a variable after you initialize it results in confusing, harder to understand code.

Secondly, when you use var, you can declare the same variable as many times as you like, but with let you can't. The following would work:
var myName = 'Chris';
var myName = 'Bob';
But the following would throw an error on the second line:
let myName = 'Chris';
let myName = 'Bob';
You'd have to do this instead:
let myName = 'Chris';
myName = 'Bob';

Conditional statements

A conditional statement is a set of commands that executes if a specified condition is true. JavaScript supports two conditional statements: if...else and switch.

if...else statement

Use the if statement to execute a statement if a logical condition is true. Use the optional else clause to execute a statement if the condition is false.
An if statement looks like this:
if (condition) {
  statement_1;
} else {
  statement_2;
}
Here, the condition can be any expression that evaluates to true or false. (See Boolean for an explanation of what evaluates to true and false.)
If condition evaluates to truestatement_1 is executed. Otherwise, statement_2 is executed. statement_1 and statement_2 can be any statement, including further nested if statements.
You can also compound the statements using else if to have multiple conditions tested in sequence, as follows:
if (condition_1) {
  statement_1;
} else if (condition_2) {
  statement_2;
} else if (condition_n) {
  statement_n;
} else {
  statement_last;
} 
In the case of multiple conditions, only the first logical condition which evaluates to true will be executed. To execute multiple statements, group them within a block statement ({ … }).

Best practice

In general, it's good practice to always use block statements—especially when nesting if statements:
if (condition) {
  statement_1_runs_if_condition_is_true;
  statement_2_runs_if_condition_is_true;
} else {
  statement_3_runs_if_condition_is_false;
  statement_4_runs_if_condition_is_false;
}
It's unwise to use simple assignments in a conditional expression, because the assignment can be confused with equality when glancing over the code.
For example, do not write code like this:
// Prone to being misread as "x == y"
if (x = y) {
  /* statements here */
}
If you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment, like this:
if ((x = y)) {
  /* statements here */
}

Falsy values

The following values evaluate to false (also known as Falsy values):
  • false
  • undefined
  • null
  • 0
  • NaN
  • the empty string ("")
All other values—including all objects—evaluate to true when passed to a conditional statement.
Caution: Do not confuse the primitive boolean values true and false with the true and false values of the Boolean object!
For example:
var b = new Boolean(false);
if (b)         // this condition evaluates to true
if (b == true) // this condition evaluates to false

Example

In the following example, the function checkData returns true if the number of characters in a Text object is three. Otherwise, it displays an alert and returns false.
function checkData() {
  if (document.form1.threeChar.value.length == 3) {
    return true;
  } else {
    alert(
        'Enter exactly three characters. ' +
        `${document.form1.threeChar.value} is not valid.`);
    return false;
  }
}

switch statement

switch statement allows a program to evaluate an expression and attempt to match the expression's value to a case label. If a match is found, the program executes the associated statement.
switch statement looks like this:
switch (expression) {
  case label_1:
    statements_1
    [break;]
  case label_2:
    statements_2
    [break;]
    …
  default:
    statements_def
    [break;]
}
JavaScript evaluates the above switch statement as follows:
  • The program first looks for a case clause with a label matching the value of expression and then transfers control to that clause, executing the associated statements.
  • If no matching label is found, the program looks for the optional default clause:
    • If a default clause is found, the program transfers control to that clause, executing the associated statements.
    • If no default clause is found, the program resumes execution at the statement following the end of switch.
    • (By convention, the default clause is written as the last clause, but it does not need to be so.)

break statements

The optional break statement associated with each case clause ensures that the program breaks out of switch once the matched statement is executed, and then continues execution at the statement following switch. If break is omitted, the program continues execution inside the switch statement (and will evaluate the next case, and so on).
Example
In the following example, if fruittype evaluates to 'Bananas', the program matches the value with case 'Bananas' and executes the associated statement. When break is encountered, the program exits the switch and continues execution from the statement following switch. If break were omitted, the statement for case 'Cherries' would also be executed.
switch (fruittype) {
  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.');
    break;
  case 'Cherries':
    console.log('Cherries are $3.00 a pound.');
    break;
  case 'Mangoes':
    console.log('Mangoes are $0.56 a pound.');
    break;
  case 'Papayas':
    console.log('Mangoes and papayas are $2.79 a pound.');
    break;
  default:
   console.log(`Sorry, we are out of ${fruittype}.`);
}
console.log("Is there anything else you'd like?");

Exception handling statements

You can throw exceptions using the throw statement and handle them using the try...catch statements.

Exception types

Just about any object can be thrown in JavaScript. Nevertheless, not all thrown objects are created equal. While it is common to throw numbers or strings as errors, it is frequently more effective to use one of the exception types specifically created for this purpose:

throw statement

Use the throw statement to throw an exception. A throw statement specifies the value to be thrown:
throw expression;
You may throw any expression, not just expressions of a specific type. The following code throws several exceptions of varying types:
throw 'Error2';   // String type
throw 42;         // Number type
throw true;       // Boolean type
throw {toString: function() { return "I'm an object!"; } };
Note: You can specify an object when you throw an exception. You can then reference the object's properties in the catch block.
// Create an object type UserException
function UserException(message) {
  this.message = message;
  this.name = 'UserException';
}

// Make the exception convert to a pretty string when used as a string 
// (e.g., by the error console)
UserException.prototype.toString = function() {
  return `${this.name}: "${this.message}"`;
}

// Create an instance of the object type and throw it
throw new UserException('Value too high');

try...catch statement

The try...catch statement marks a block of statements to try, and specifies one or more responses should an exception be thrown. If an exception is thrown, the try...catch statement catches it.
The try...catch statement consists of a try block, which contains one or more statements, and a catch block, containing statements that specify what to do if an exception is thrown in the try block.
In other words, you want the try block to succeed—but if it does not, 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 block. If no exception is thrown in the try block, the catch block is skipped. The finally block executes after the try and catch blocks execute but before the statements following the try...catch statement.
The following example uses a try...catch statement. The example calls a function that retrieves a month name from an array based on the value passed to the function. If the value does not correspond to a month number (112), an exception is thrown with the value "InvalidMonthNo" and the statements in the catch block set the monthName variable to 'unknown'.
function getMonthName(mo) {
  mo = mo - 1; // Adjust month number for array index (1 = Jan, 12 = Dec)
  let months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
                'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  if (months[mo]) {
    return months[mo];
  } else {
    throw 'InvalidMonthNo'; // throw keyword is used here
  }
}

try { // statements to try
  monthName = getMonthName(myMonth); // function could throw exception
}
catch (e) {
  monthName = 'unknown';
  logMyErrors(e); // pass exception object to error handler (i.e. your own function)
}

The catch block

You can use a catch block to handle all exceptions that may be generated in the try block.
catch (catchID) {
  statements
}
The catch block specifies an identifier (catchID in the preceding syntax) that holds the value specified by the throw statement. You can use this identifier to get information about the exception that was thrown.
JavaScript creates this identifier when the catch block is entered. The identifier lasts only for the duration of the catch block. Once the catch block finishes executing, the identifier no longer exists.
For example, the following code throws an exception. When the exception occurs, control transfers to the catch block.
try {
  throw 'myException'; // generates an exception
}
catch (err) {
  // statements to handle any exceptions
  logMyErrors(err);    // pass exception object to error handler
}
Best practice: When logging errors to the console inside a catch block, using console.error() rather than console.log() is advised for debugging. It formats the message as an error, and adds it to the list of error messages generated by the page. 

The finally block

The finally block contains statements to be executed after the try and catch blocks execute. Additionally, the finally block executes before the code that follows the try…catch…finally statement.
It is also important to note that the finally block will execute whether or not an exception is thrown. If an exception is thrown, however, the statements in the finally block execute even if no catch block handles the exception that was thrown.
You can use the finally block 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 block closes the file before the script fails. Using finally here ensures that the file is never left open, even if an error occurs.
openMyFile();
try {
  writeMyFile(theData); // This may throw an error
} catch(e) {  
  handleError(e); // If an error occurred, handle it
} finally {
  closeMyFile(); // Always close the resource
}
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:
function f() {
  try {
    console.log(0);
    throw 'bogus';
  } catch(e) {
    console.log(1);
    return true;    // this return statement is suspended
                    // until finally block has completed
    console.log(2); // not reachable
  } finally {
    console.log(3);
    return false;   // overwrites the previous "return"
    console.log(4); // not reachable
  }
  // "return false" is executed now  
  console.log(5);   // not reachable
}
console.log(f()); // 0, 1, 3, false
Overwriting of return values by the finally block also applies to exceptions thrown or re-thrown inside of the catch block:
function f() {
  try {
    throw 'bogus';
  } catch(e) {
    console.log('caught inner "bogus"');
    throw e; // this throw statement is suspended until 
             // finally block has completed
  } finally {
    return false; // overwrites the previous "throw"
  }
  // "return false" is executed now
}

try {
  console.log(f());
} catch(e) {
  // this is never reached! 
  // while f() executes, the `finally` block returns false, 
  // which overwrites the `throw` inside the above `catch`
  console.log('caught outer "bogus"');
}

// OUTPUT
// caught inner "bogus"
// false

Nesting try...catch statements

You can nest one or more try...catch statements.
If an inner try...catch statement does not have a catch block:
  1. it must contain a finally block, and
  2. the enclosing try...catch statement's catch block is checked for a match.
For more information, see nested try-blocks on the try...catch reference page.

Utilizing Error objects

Depending on the type of error, you may be able to use the name and message properties to get a more refined message.
The name property provides the general class of Error (such as DOMException or Error), while message generally provides a more succinct message than one would get by converting the error object to a string.
If you are throwing your own exceptions, in order to take advantage of these properties (such as if your catch block doesn't discriminate between your own exceptions and system ones), you can use the Error constructor.
For example:
function doSomethingErrorProne() {
  if (ourCodeMakesAMistake()) {
    throw (new Error('The message'));
  } else {
    doSomethingToGetAJavascriptError();
  }
}try {
  doSomethingErrorProne();
} catch (e) {               // NOW, we actually use `console.error()`
  console.error(e.name);    // logs 'Error'
  console.error(e.message); // logs 'The message', or a JavaScript error message
}

for statement

for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and C for loop.
for statement looks as follows:
for ([initialExpression]; [condition]; [incrementExpression])
  statement
When a for loop executes, the following occurs:
  1. The initializing expression initialExpression, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity. This expression can also declare variables.
  2. The condition expression is evaluated. If the value of condition is true, the loop statements execute. If the value of condition is false, the for loop terminates. (If the condition expression is omitted entirely, the condition is assumed to be true.)
  3. The statement executes. To execute multiple statements, use a block statement ({ ... }) to group those statements.
  4. If present, the update expression incrementExpression is executed.
  5. Control returns to Step 2.

Example

In the example below, the function contains a for statement that counts the number of selected options in a scrolling list (a <select> element that allows multiple selections). The for statement declares the variable i and initializes it to 0. It checks that i is less than the number of options in the <select> element, performs the succeeding if statement, and increments i by after each pass through the loop.
<form name="selectForm">
  <p>
    <label for="musicTypes">Choose some music types, then click the button below:</label>
    <select id="musicTypes" name="musicTypes" multiple="multiple">
      <option selected="selected">R&B</option>
      <option>Jazz</option>
      <option>Blues</option>
      <option>New Age</option>
      <option>Classical</option>
      <option>Opera</option>
    </select>
  </p>
  <p><input id="btn" type="button" value="How many are selected?" /></p>
</form>

<script>
function howMany(selectObject) {
  let numberSelected = 0;
  for (let i = 0; i < selectObject.options.length; i++) {
    if (selectObject.options[i].selected) {
      numberSelected++;
    }
  }
  return numberSelected;
}

let btn = document.getElementById('btn');
btn.addEventListener('click', function() {
  alert('Number of options selected: ' + howMany(document.selectForm.musicTypes));
});
</script>

do...while statement

The do...while statement repeats until a specified condition evaluates to false.
do...while statement looks as follows:
do
  statement
while (condition);
statement is always executed once before the condition is checked. (To execute multiple statements, use a block statement ({ ... }) to group those statements.)
If condition is true, the statement executes again. At the end of every execution, the condition is checked. When the condition is false, execution stops, and control passes to the statement following do...while.

Example

In the following example, the do loop iterates at least once and reiterates until i is no longer less than 5.
let i = 0;
do {
  i += 1;
  console.log(i);
} while (i < 5);

while statement

while statement executes its statements as long as a specified condition evaluates to true. A while statement looks as follows:
while (condition)
  statement
If the condition becomes falsestatement within the loop stops executing and control passes to the statement following the loop.
The condition test occurs before statement in the loop is executed. If the condition returns truestatement is executed and the condition is tested again. If the condition returns false, execution stops, and control is passed to the statement following while.
To execute multiple statements, use a block statement ({ ... }) to group those statements.

Example 1

The following while loop iterates as long as n is less than 3:
let n = 0;
let x = 0;
while (n < 3) {
  n++;
  x += n;
}
With each iteration, the loop increments n and adds that value to x. Therefore, x and n take on the following values:
  • After the first pass: n = 1 and x = 1
  • After the second pass: n = 2 and x = 3
  • After the third pass: n = 3 and x = 6
After completing the third pass, the condition n < 3 is no longer true, so the loop terminates.

Example 2

Avoid infinite loops. Make sure the condition in a loop eventually becomes false—otherwise, the loop will never terminate! The statements in the following while loop execute forever because the condition never becomes false:
// Infinite loops are bad!
while (true) {
  console.log('Hello, world!');
}

labeled statement

label provides a statement with an identifier that lets you refer to it elsewhere in your program. For example, you can use a label to identify a loop, and then use the break or continue statements to indicate whether a program should interrupt the loop or continue its execution.
The syntax of the labeled statement looks like the following:
label :
   statement
The value of label may be any JavaScript identifier that is not a reserved word. The statement that you identify with a label may be any statement.

Example

In this example, the label markLoop identifies a while loop.
markLoop:
while (theMark === true) {
   doSomething();
}

break statement

Use the break statement to terminate a loop, switch, or in conjunction with a labeled statement.
  • When you use break without a label, it terminates the innermost enclosing whiledo-whilefor, or switch immediately and transfers control to the following statement.
  • When you use break with a label, it terminates the specified labeled statement.
The syntax of the break statement looks like this:
break;
break [label];
  1. The first form of the syntax terminates the innermost enclosing loop or switch.
  2. The second form of the syntax terminates the specified enclosing labeled statement.

Example 1

The following example iterates through the elements in an array until it finds the index of an element whose value is theValue:
for (let i = 0; i < a.length; i++) {
  if (a[i] === theValue) {
    break;
  }
}

Example 2: Breaking to a label

let x = 0;
let z = 0;
labelCancelLoops: while (true) {
  console.log('Outer loops: ' + x);
  x += 1;
  z = 1;
  while (true) {
    console.log('Inner loops: ' + z);
    z += 1;
    if (z === 10 && x === 10) {
      break labelCancelLoops;
    } else if (z === 10) {
      break;
    }
  }
}

continue statement

The continue statement can be used to restart a whiledo-whilefor, or label statement.
  • When you use continue without a label, it terminates the current iteration of the innermost enclosing whiledo-while, or for statement and continues execution of the loop with the next iteration. In contrast to the break statement, continue does not terminate the execution of the loop entirely. In a while loop, it jumps back to the condition. In a for loop, it jumps to the increment-expression.
  • When you use continue with a label, it applies to the looping statement identified with that label.
The syntax of the continue statement looks like the following:
continue [label];

Example 1

The following example shows a while loop with a continue statement that executes when the value of i is 3. Thus, n takes on the values 137, and 12.
let i = 0;
let n = 0;
while (i < 5) {
  i++;
  if (i === 3) {
    continue;
  }
  n += i;
  console.log(n);
}
//1,3,7,12


let i = 0; 
let n = 0; 
while (i < 5) { 
  i++; 
  if (i === 3) { 
     // continue; 
  } 
  n += i; 
  console.log(n);
}
// 1,3,6,10,15

Example 2

A statement labeled checkiandj contains a statement labeled checkj. If continue is encountered, the program terminates the current iteration of checkj and begins the next iteration. Each time continue is encountered, checkj reiterates until its condition returns false. When false is returned, the remainder of the checkiandj statement is completed, and checkiandj reiterates until its condition returns false. When false is returned, the program continues at the statement following checkiandj.
If continue had a label of checkiandj, the program would continue at the top of the checkiandj statement.
let i = 0;
let j = 10;
checkiandj:
  while (i < 4) {
    console.log(i);
    i += 1;
    checkj:
      while (j > 4) {
        console.log(j);
        j -= 1;
        if ((j % 2) === 0) {
          continue checkj;
        }
        console.log(j + ' is odd.');
      }
      console.log('i = ' + i);
      console.log('j = ' + j);
  }

for...in statement

The for...in statement iterates a specified variable over all the enumerable properties of an object. For each distinct property, JavaScript executes the specified statements. A for...in statement looks as follows:
for (variable in object)
  statement

Example

The following function takes as its argument an object and the object's name. It then iterates over all the object's properties and returns a string that lists the property names and their values.
function dump_props(obj, obj_name) {
  let result = '';
  for (let i in obj) {
    result += obj_name + '.' + i + ' = ' + obj[i] + '<br>';
  }
  result += '<hr>';
  return result;
}
For an object car with properties make and modelresult would be:
car.make = Ford
car.model = Mustang

Arrays

Although it may be tempting to use this as a way to iterate over Array elements, the for...in statement will return the name of your user-defined properties in addition to the numeric indexes.
Therefore, it is better to use a traditional for loop with a numeric index when iterating over arrays, because the for...in statement iterates over user-defined properties in addition to the array elements, if you modify the Array object (such as adding custom properties or methods).

for...of statement

The for...of statement creates a loop Iterating over iterable objects (including ArrayMapSetarguments object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
for (variable of object)
  statement
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:

const arr = [3, 5, 7];
arr.foo = 'hello';

for (let i in arr) {
   console.log(i); // logs "0", "1", "2", "foo"
}

for (let i of arr) {
   console.log(i); // logs 3, 5, 7
}
Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure—a set of statements that performs a task or calculates a value. To use a function, you must define it somewhere in the scope from which you wish to call it.
See also the exhaustive reference chapter about JavaScript functions to get to know the details.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.