The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.
The examples below make use of the log function of the console object present in most browsers for standard text output.
The JavaScript standard library lacks an official standard text output function (with the exception of document.write
). Given that JavaScript is mainly used for client-side scripting within modern web browsers, and that almost all Web browsers provide the alert function, alert
can also be used, but is not commonly used.
Brendan Eich summarized the ancestry of the syntax in the first paragraph of the JavaScript 1.1 specification[1] [2] as follows:
JavaScript is case sensitive. It is common to start the name of a constructor with a capitalised letter, and the name of a function or variable with a lower-case letter.
Example:
Unlike in C, whitespace in JavaScript source can directly impact semantics. Semicolons end statements in JavaScript. Because of automatic semicolon insertion (ASI), some statements that are well formed when a newline is parsed will be considered complete, as if a semicolon were inserted just prior to the newline. Some authorities advise supplying statement-terminating semicolons explicitly, because it may lessen unintended effects of the automatic semicolon insertion.[3]
There are two issues: five tokens can either begin a statement or be the extension of a complete statement; and five restricted productions, where line breaks are not allowed in certain positions, potentially yielding incorrect parsing.
The five problematic tokens are the open parenthesis "(
", open bracket "[
", slash "/
", plus "+
", and minus "-
". Of these, the open parenthesis is common in the immediately invoked function expression pattern, and open bracket occurs sometimes, while others are quite rare. An example:
// Treated as:// a = b + c(d + e).foo;with the suggestion that the preceding statement be terminated with a semicolon.
Some suggest instead the use of leading semicolons on lines starting with '(
' or '<nowiki>[</nowiki>
', so the line is not accidentally joined with the previous one. This is known as a defensive semicolon, and is particularly recommended, because code may otherwise become ambiguous when it is rearranged. For example:
// Treated as:// a = b + c;// (d + e).foo;Initial semicolons are also sometimes used at the start of JavaScript libraries, in case they are appended to another library that omits a trailing semicolon, as this can result in ambiguity of the initial statement.
The five restricted productions are return
, throw
, break
, continue
, and post-increment/decrement. In all cases, inserting semicolons does not fix the problem, but makes the parsed syntax clear, making the error easier to detect. return
and throw
take an optional value, while break
and continue
take an optional label. In all cases, the advice is to keep the value or label on the same line as the statement. This most often shows up in the return statement, where one might return a large object literal, which might be accidentally placed starting on a new line. For post-increment/decrement, there is potential ambiguity with pre-increment/decrement, and again it is recommended to simply keep these on the same line.
// Returns undefined. Treated as:// return;// a + b;// Should be written as:// return a + b;
See main article: Comment (computer programming). Comment syntax is the same as in C++, Swift and many other languages.
/* this is a long, multi-line comment about my script. May it one day be great. */
/* Comments /* may not be nested */ Syntax error */
See main article: Variable (programming).
Variables in standard JavaScript have no type attached, so any value (each value has a type) can be stored in any variable. Starting with ES6, the 6th version of the language, variables could be declared with var
for function scoped variables, and let
or const
which are for block level variables. Before ES6, variables could only be declared with a var
statement. Values assigned to variables declared with const
cannot be changed, but their properties can. var
should no longer be used since let
and const
are supported by modern browsers.[4] A variable's identifier must start with a letter, underscore (_
), or dollar sign ($
), while subsequent characters can also be digits (0-9
). JavaScript is case sensitive, so the uppercase characters "A" through "Z" are different from the lowercase characters "a" through "z".
Starting with JavaScript 1.5, ISO 8859-1 or Unicode letters (or \uXXXX
Unicode escape sequences) can be used in identifiers.[5] In certain JavaScript implementations, the at sign (@) can be used in an identifier, but this is contrary to the specifications and not supported in newer implementations.
Variables declared with var
are lexically scoped at a function level, while ones with let
or const
have a block level scope. Since declarations are processed before any code is executed, a variable can be assigned to and used prior to being declared in the code.[6] This is referred to as , and it is equivalent to variables being forward declared at the top of the function or block.[7]
With var
, let
, and const
statements, only the declaration is hoisted; assignments are not hoisted. Thus a statement in the middle of the function is equivalent to a declaration statement at the top of the function, and an assignment statement at that point in the middle of the function. This means that values cannot be accessed before they are declared; forward reference is not possible. With var
a variable's value is undefined
until it is initialized. Variables declared with let
or const
cannot be accessed until they have been initialized, so referencing such variables before will cause an error.
Function declarations, which declare a variable and assign a function to it, are similar to variable statements, but in addition to hoisting the declaration, they also hoist the assignment – as if the entire statement appeared at the top of the containing function – and thus forward reference is also possible: the location of a function statement within an enclosing function is irrelevant. This is different from a function expression being assigned to a variable in a var
, let
, or const
statement.
So, for example,
Block scoping can be produced by wrapping the entire block in a function and then executing it – this is known as the immediately-invoked function expression pattern – or by declaring the variable using the let
keyword.
Variables declared outside a scope are global. If a variable is declared in a higher scope, it can be accessed by child scopes.
When JavaScript tries to resolve an identifier, it looks in the local scope. If this identifier is not found, it looks in the next outer scope, and so on along the scope chain until it reaches the global scope where global variables reside. If it is still not found, JavaScript will raise a ReferenceError
exception.
When assigning an identifier, JavaScript goes through exactly the same process to retrieve this identifier, except that if it is not found in the global scope, it will create the "variable" in the scope where it was created.[8] As a consequence, a variable never declared will be global, if assigned. Declaring a variable (with the keyword var
) in the global scope (i.e. outside of any function body (or block in the case of let/const)), assigning a never declared identifier or adding a property to the global object (usually window) will also create a new global variable.
Note that JavaScript's strict mode forbids the assignment of an undeclared variable, which avoids global namespace pollution.
Here are some examples of variable declarations and scope:
function f
f;
console.log(z); // This line will raise a ReferenceError exception, because the value of z is no longer available
for (const i of [1,2,3]) console.log(i); //will not raise an exception. i is not reassigned but recreated in every iteration
const pi; // throws a SyntaxError: Missing initializer in const declaration
See main article: Primitive data type. The JavaScript language provides six primitive data types:
Some of the primitive data types also provide a set of named values that represent the extents of the type boundaries. These named values are described within the appropriate sections below.
See main article: Undefined value.
The value of "undefined" is assigned to all uninitialized variables, and is also returned when checking for object properties that do not exist. In a Boolean context, the undefined value is considered a false value.
Note: undefined is considered a genuine primitive type. Unless explicitly converted, the undefined value may behave unexpectedly in comparison to other types that evaluate to false in a logical context.
Note: There is no built-in language literal for undefined. Thus is not a foolproof way to check whether a variable is undefined, because in versions before ECMAScript 5, it is legal for someone to write . A more robust approach is to compare using .
Functions like this won't work as expected:
Here, calling isUndefined(my_var)
raises a if is an unknown identifier, whereas doesn't.
Numbers are represented in binary as IEEE 754 floating point doubles. Although this format provides an accuracy of nearly 16 significant digits, it cannot always exactly represent real numbers, including fractions.
This becomes an issue when comparing or formatting numbers. For example:
As a result, a routine such as the method should be used to round numbers whenever they are formatted for output.
Numbers may be specified in any of these notations:
There's also a numeric separator, (the underscore), introduced in ES2021:
// Support with binary, octals and hex0b0000_0000_0101_1011;0o0001_3520_0237_1327;0xFFFF_FFFF_FFFF_FFFE;
// But you can't use them next to a non-digit number part, or at the start or end_12; // Variable is not defined (the underscore makes it a variable identifier)12_; // Syntax error (cannot be at the end of numbers)12_.0; // Syntax error (doesn't make sense to put a separator next to the decimal point)12._0; // Syntax error12e_6; // Syntax error (next to "e", a non-digit. Doesn't make sense to put a separator at the start)1000____0000; // Syntax error (next to "_", a non-digit. Only 1 separator at a time is allowed
The extents +∞, -∞ and NaN (Not a Number) of the number type may be obtained by two program expressions:
Infinity and NaN are numbers:
These three special values correspond and behave as the IEEE-754 describes them.
The Number constructor (used as a function), or a unary + or -, may be used to perform explicit numeric conversion:
When used as a constructor, a numeric wrapper object is created (though it is of little use):
However, NaN is not equal to itself:
nan); // true
// You can use the isNaN methods to check for NaNconsole.log(isNaN("converted to NaN")); // trueconsole.log(isNaN(NaN)); // trueconsole.log(Number.isNaN("not converted")); // falseconsole.log(Number.isNaN(NaN)); // true
BigInts can be used for arbitrarily large integers. Especially whole numbers larger than 253 - 1, which is the largest number JavaScript can reliably represent with the Number primitive and represented by the Number.MAX_SAFE_INTEGER constant.
When dividing BigInts, the results are truncated.
A string in JavaScript is a sequence of characters. In JavaScript, strings can be created directly (as literals) by placing the series of characters between double (") or single (') quotes. Such strings must be written on a single line, but may include escaped newline characters (such as \n). The JavaScript standard allows the backquote character (`, a.k.a. grave accent or backtick) to quote multiline literal strings, as well as template literals, which allow for interpolation of type-coerced evaluated expressions within a string.[9]
// Template literals type-coerce evaluated expressions and interpolate them into the string.const templateLiteral = `This is what is stored in anotherGreeting: $.`;console.log(templateLiteral); // 'This is what is stored in anotherGreeting: 'Greetings, people of Earth.
Individual characters within a string can be accessed using the method (provided by). This is the preferred way when accessing individual characters within a string, because it also works in non-modern browsers:
In modern browsers, individual characters within a string can be accessed (as strings with only a single character) through the same notation as arrays:
However, JavaScript strings are immutable:
Applying the equality operator ("
"hello, World"); // Here compare2 contains ... // ... false since the ... // ... first characters ... // ... of both operands ... // ... are not of the same case.
Quotes of the same type cannot be nested unless they are escaped.
The constructor creates a string object (an object wrapping a string):
These objects have a method returning the primitive string wrapped within them:
Equality between two objects does not behave as with string primitives:
s2.valueOf; // Is true.
JavaScript provides a Boolean data type with and literals. The operator returns the string for these primitive types. When used in a logical context,,,,,, and the empty string evaluate as due to automatic type conversion. All other values (the complement of the previous list) evaluate as, including the strings, and any object.
Automatic type coercion by the equality comparison operators (==
and !=
) can be avoided by using the type checked comparison operators (===
and !==
).
When type conversion is required, JavaScript converts,,, or operands as follows:[10]
Douglas Crockford advocates the terms "truthy" and "falsy" to describe how values of various types behave when evaluated in a logical context, especially in regard to edge cases.[11] The binary logical operators returned a Boolean value in early versions of JavaScript, but now they return one of the operands instead. The left–operand is returned, if it can be evaluated as :, in the case of conjunction: (a && b
), or, in the case of disjunction: (a || b
); otherwise the right–operand is returned. Automatic type coercion by the comparison operators may differ for cases of mixed Boolean and number-compatible operands (including strings that can be evaluated as a number, or objects that can be evaluated as such a string), because the Boolean operand will be compared as a numeric value. This may be unexpected. An expression can be explicitly cast to a Boolean primitive by doubling the logical negation operator:, using the function, or using the conditional operator: (c ? t : f
).
2 ← 2console.log(false
2 ← 2console.log(true
2 ← "2"console.log(false
2 ← "2"console.log(true
NaN
console.log(NaN
// Type checked comparison (no conversion of types and values)console.log(true
// Explicit type coercionconsole.log(true
!!0); // false... data types match, but values differconsole.log(1 ? true : false); // true.... only ±0 and NaN are "falsy" numbersconsole.log("0" ? true : false); // true.... only the empty string is "falsy"console.log(Boolean); // true.... all objects are "truthy"
The new operator can be used to create an object wrapper for a Boolean primitive. However, the operator does not return for the object wrapper, it returns . Because all objects evaluate as, a method such as, or, must be used to retrieve the wrapped value. For explicit coercion to the Boolean type, Mozilla recommends that the function (without) be used in preference to the Boolean object.
if (0 || -0 || "" || null || undefined || b.valueOf || !new Boolean || !t) else if ([] && && b && typeof b
"false")
New in ECMAScript6. A Symbol is a unique and immutable identifier.
Example:
const symbolObject = ;const normalObject = ;
// since x and y are unique,// they can be used as unique keys in an objectsymbolObject[x] = 1;symbolObject[y] = 2;
symbolObject[x]; // => 1symbolObject[y]; // => 2
// as compared to normal numeric keysnormalObject[1] = 1;normalObject[1] = 2; // overrides the value of 1
normalObject[1]; // => 2
// changing the value of x does not change the key stored in the objectx = Symbol(3);symbolObject[x]; // => undefined
// changing x back just creates another unique Symbolx = Symbol(1);symbolObject[x]; // => undefined
There are also well known symbols.
One of which is Symbol.iterator
; if something implements Symbol.iterator
, it's iterable:
const xIterator = x[Symbol.iterator]; // The [Symbol.iterator] function should provide an iterator for xxIterator.next; // xIterator.next; // xIterator.next; // xIterator.next; // xIterator.next; // xIterator.next; //
// for..of loops automatically iterate valuesfor (const value of x)
// Sets are also iterable:[Symbol.iterator] in Set.prototype; // true
for (const value of new Set(['apple', 'orange']))
The JavaScript language provides a handful of native objects. JavaScript native objects are considered part of the JavaScript specification. JavaScript environment notwithstanding, this set of objects should always be available.
See main article: Array data type. An Array is a JavaScript object prototyped from the Array
constructor specifically designed to store data values indexed by integer keys. Arrays, unlike the basic Object type, are prototyped with methods and properties to aid the programmer in routine tasks (for example, join
, slice
, and push
).
As in the C family, arrays use a zero-based indexing scheme: A value that is inserted into an empty array by means of the push
method occupies the 0th index of the array.
Arrays have a length
property that is guaranteed to always be larger than the largest integer index used in the array. It is automatically updated, if one creates a property with an even larger index. Writing a smaller number to the length
property will remove larger indices.
Elements of Array
s may be accessed using normal object property access notation:
The above two are equivalent. It's not possible to use the "dot"-notation or strings with alternative representations of the number:
Declaration of an array can use either an Array
literal or the Array
constructor:
// Array literalsmyArray = [1, 2]; // length of 2myArray = [1, 2,]; // same array - You can also have an extra comma at the end
// It's also possible to not fill in parts of the arraymyArray = [0, 1, /* hole */, /* hole */, 4, 5]; // length of 6myArray = [0, 1, /* hole */, /* hole */, 4, 5,]; // same arraymyArray = [0, 1, /* hole */, /* hole */, 4, 5, /* hole */,]; // length of 7
// With the constructormyArray = new Array(0, 1, 2, 3, 4, 5); // length of 6myArray = new Array(365); // an empty array with length 365
Arrays are implemented so that only the defined elements use memory; they are "sparse arrays". Setting and only uses space for these two elements, just like any other object. The length
of the array will still be reported as 58. The maximum length of an array is 4,294,967,295 which corresponds to 32-bit binary number (11111111111111111111111111111111)2.
One can use the object declaration literal to create objects that behave much like associative arrays in other languages:
One can use the object and array declaration literals to quickly create arrays that are associative, multidimensional, or both. (Technically, JavaScript does not support multidimensional arrays, but one can mimic them with arrays-of-arrays.)
const dogs = ;dogs["spot"]["size"]; // results in "small"dogs.rover.color; // results in "brown"
A Date
object stores a signed millisecond count with zero representing 1970-01-01 00:00:00 UT and a range of ±108 days. There are several ways of providing arguments to the Date
constructor. Note that months are zero-based.
Methods to extract fields are provided, as well as a useful toString
:
// Displays '2010-3-1 14:25:30':console.log(d.getFullYear + '-' + (d.getMonth + 1) + '-' + d.getDate + ' ' + d.getHours + ':' + d.getMinutes + ':' + d.getSeconds);
// Built-in toString returns something like 'Mon Mar 01 2010 14:25:30 GMT-0500 (EST)':console.log(d);
Custom error messages can be created using the Error
class:
These can be caught by try...catch...finally blocks as described in the section on exception handling.
The object contains various math-related constants (for example,) and functions (for example, cosine). (Note that the object has no constructor, unlike or . All its methods are "static", that is "class" methods.) All the trigonometric functions use angles expressed in radians, not degrees or grads.
Property | Returned value rounded to 5 digits | Description | |
---|---|---|---|
2.7183 | Natural logarithm base | ||
0.69315 | Natural logarithm of 2 | ||
2.3026 | Natural logarithm of 10 | ||
1.4427 | Logarithm to the base 2 of | ||
0.43429 | Logarithm to the base 10 of | ||
3.14159 | circumference/diameter of a circle | ||
0.70711 | Square root of ½ | ||
1.4142 | Square root of 2 |
Example | Returned value rounded to 5 digits | Description | |
---|---|---|---|
2.3 | Absolute value | ||
= 45° | Arccosine | ||
= 45° | Arcsine | ||
= 45° | Half circle arctangent (to) | ||
= | Whole circle arctangent (to) | ||
2 | Ceiling: round up to smallest integer ≥ argument | ||
0.70711 | Cosine | ||
2.7183 | Exponential function raised to this power | ||
1 | Floor: round down to largest integer ≤ argument | ||
1 | Natural logarithm, base | ||
1 | Maximum: | ||
Minimum: | |||
9 | Exponentiation (raised to the power of): gives xy | ||
e.g. 0.17068 | Pseudorandom number between 0 (inclusive) and 1 (exclusive) | ||
2 | Round to the nearest integer; half fractions are rounded up (e.g. 1.5 rounds to 2) | ||
0.70711 | Sine | ||
7 | Square root | ||
1 | Tangent |
See main article: Regular expression.
// Here are some examplesif (/Tom/.test("My name is Tom")) console.log("Hello Tom!");console.log("My name is Tom".search(/Tom/)); //
"My name is John"
if (/\d/.test('0')) console.log('Digit');if (/[0-9]/.test('6')) console.log('Digit');if (/[13579]/.test('1')) console.log('Odd number');if (/\S\S\s\S\S\S\S/.test('My name')) console.log('Format OK');if (/\w\w\w/.test('Tom')) console.log('Hello Tom');if (/[a-zA-Z]/.test('B')) console.log('Letter');
if (/T.m/.test('Tom')) console.log ('Hi Tom, Tam or Tim');if (/A|B/.test("A")) console.log ('A or B');
if (/ab?c/.test("ac")) console.log("OK"); // match: "ac", "abc"if (/ab*c/.test("ac")) console.log("OK"); // match: "ac", "abc", "abbc", "abbbc" etc.if (/ab+c/.test("abc")) console.log("OK"); // match: "abc", "abbc", "abbbc" etc.if (/abc/.test("abbbc")) console.log("OK"); // match: "abbbc"if (/abc/.test("abbbc")) console.log("OK"); // match: "abbbc", "abbbbc", "abbbbbc" etc.if (/abc/.test("abc")) console.log("OK"); // match: "abc", "abbc", "abbbc"
if (/^My/.test("My name is Tom")) console.log ("Hi!");if (/Tom$/.test("My name is Tom")) console.log ("Hi Tom!");
if (/water(mark)?/.test("watermark")) console.log("Here is water!"); // match: "water", "watermark",if (/(Tom)|(John)/.test("John")) console.log("Hi Tom or John!");
console.log("hi tom!".replace(/Tom/i, "John")); //
"ratutam"console.log("ratatam".replace(/ta/g, "tu")); //
my_array = my_string.match(my_expression);// examplemy_array = "We start at 11:30, 12:15 and 16:45".match(/\d\d:\d\d/g); // my_array
Every function in JavaScript is an instance of the Function
constructor:
The add function above may also be defined using a function expression:
In ES6, arrow function syntax was added, allowing functions that return a value to be more concise. They also retain the this
of the global object instead of inheriting it from where it was called / what it was called on, unlike the function {}
expression.
add(1, 2); // => 3addImplicit(1, 2) // => 3
For functions that need to be hoisted, there is a separate expression:
Hoisting allows you to use the function before it is "declared":
A function instance has properties and methods.
console.log(subtract.length); // => 2, arity of the function (number of arguments)console.log(subtract.toString);
/*"function subtract(x, y) "
The '+' operator is overloaded: it is used for string concatenation and arithmetic addition. This may cause problems when inadvertently mixing strings and numbers. As a unary operator, it can convert a numeric string to a number.
// Add two numbersconsole.log(2 + 6); // displays 8
// Adding a number and a string results in concatenation (from left to right)console.log(2 + '2'); // displays 22console.log('$' + 3 + 4); // displays $34, but $7 may have been expectedconsole.log('$' + (3 + 4)); // displays $7console.log(3 + 4 + '7'); // displays 77, numbers stay numbers until a string is added
// Convert a string to a number using the unary plusconsole.log(+'2'
Similarly, the '*' operator is overloaded: it can convert a string into a number.
JavaScript supports the following binary arithmetic operators:
+ | addition | |
- | subtraction | |
* | multiplication | |
/ | division (returns a floating-point value) | |
% | modulo (returns the remainder) | |
** | exponentiation |
JavaScript supports the following unary arithmetic operators:
+ | unary conversion of string to number | |
- | unary negation (reverses the sign) | |
++ | increment (can be prefix or postfix) | |
-- | decrement (can be prefix or postfix) |
The modulo operator displays the remainder after division by the modulus. If negative numbers are involved, the returned value depends on the operand.
To always return a non-negative number, re-add the modulus and apply the modulo operator again:
= | assign | |
+= | add and assign | |
-= | subtract and assign | |
*= | multiply and assign | |
/= | divide and assign | |
%= | modulo and assign | |
**= | exponentiation and assign |
Assignment of object types
object_3.a = 5; // object_3 doesn't change object_2message; // displays 7 7 5
object_3 = object_2; object_3.a=4; // object_3 changes object_1 and object_2message; // displays 4 4 4
/** * Prints the console.log message */function message
In Mozilla's JavaScript, since version 1.7, destructuring assignment allows the assignment of parts of data structures to several variables at once. The left hand side of an assignment is a pattern that resembles an arbitrarily nested object/array literal containing l-lvalues at its leaves that are to receive the substructures of the assigned value.
[a, b, c] = [3, 4, 5]; // permutations[a, b, c] = [b, c, a];console.log(`$,$,$`); // displays: 4,5,3
The ECMAScript 2015 standard introduced the "...
" array operator, for the related concepts of "spread syntax"[12] and "rest parameters".[13] Object spreading was added in ECMAScript 2018.
Spread syntax provides another way to destructure arrays and objects. For arrays, it indicates that the elements should be used as the parameters in a function call or the items in an array literal. For objects, it can be used for merging objects together or overriding properties.
In other words, "...
" transforms "[...foo]
" into "[foo[0], foo[1], foo[2]]
", and "this.bar(...foo);
" into "this.bar(foo[0], foo[1], foo[2]);
", and "{ ...bar }
" into { prop: bar.prop, prop2: bar.prop2 }
.
// It can be used multiple times in the same expressionconst b = [...a, ...a]; // b = [1, 2, 3, 4, 1, 2, 3, 4];
// It can be combined with non-spread items.const c = [5, 6, ...a, 7, 9]; // c = [5, 6, 1, 2, 3, 4, 7, 9];
// For comparison, doing this without the spread operator // creates a nested array.const d = [a, a]; // d = 1, 2, 3, 4, [1, 2, 3, 4]]
// It works the same with function callsfunction foo(arg1, arg2, arg3)
// You can use it even if it passes more parameters than the function will usefoo(...a); // "1:2:3" → foo(a[0], a[1], a[2], a[3]);
// You can mix it with non-spread parametersfoo(5, ...a, 6); // "5:1:2" → foo(5, a[0], a[1], a[2], a[3], 6);
// For comparison, doing this without the spread operator// assigns the array to arg1, and nothing to the other parameters.foo(a); // "1,2,3,4:undefined:undefined"
const bar = ;
// This would copy the objectconst copy = ; // copy = ;
// "b" would be overridden hereconst override = ; // override =
When ...
is used in a function declaration, it indicates a rest parameter. The rest parameter must be the final named parameter in the function's parameter list. It will be assigned an Array
containing any arguments passed to the function in excess of the other named parameters. In other words, it gets "the rest" of the arguments passed to the function (hence the name).
foo(1, 2, 3, 4, 5); // "3" → c = [3, 4, 5]foo('a', 'b'); // "0" → c = []
Rest parameters are similar to Javascript's arguments
object, which is an array-like object that contains all of the parameters (named and unnamed) in the current function call. Unlike arguments
, however, rest parameters are true Array
objects, so methods such as .slice
and .sort
can be used on them directly.
== | equal | ||
| = | not equal | |
---|---|---|---|
> | greater than | ||
>= | greater than or equal to | ||
< | less than | ||
<= | less than or equal to | ||
=== | identical (equal and of same type) | ||
| not identical |
Variables referencing objects are equal or identical only if they reference the same object:
obj1); //trueconsole.log(obj3
See also String.
JavaScript provides four logical operators:
NOT = !a
)OR = a || b
) and conjunction (AND = a && b
)c ? t : f
)In the context of a logical operation, any expression evaluates to true except the following:
""
, <nowiki>''</nowiki>
,0
, -0
, NaN
,null
, undefined
,false
.The Boolean function can be used to explicitly convert to a primitive of type Boolean
:
true);console.log(Boolean("0")
// Only zero and NaN return falseconsole.log(Boolean(NaN)
false);console.log(Boolean(-0)
true);
// All objects return trueconsole.log(Boolean(this)
true);console.log(Boolean([])
// These types return falseconsole.log(Boolean(null)
false); // equivalent to Boolean
The NOT operator evaluates its operand as a Boolean and returns the negation. Using the operator twice in a row, as a double negative, explicitly converts an expression to a primitive of type Boolean:
!!1);console.log(!!1
Boolean(0));console.log(Boolean(0)
Boolean(!1));console.log(!""
!!"s");console.log(!!"s"
Boolean(""));console.log(Boolean("")
Boolean(!"s"));
The ternary operator can also be used for explicit conversion:
false); console.log([0]? true : false); // [0].toString
false); console.log("0"? true : false); // "0" → 0 ... (0
true); console.log([1]? true : false); // [1].toString
true); console.log("1"? true : false); // "1" → 1 ... (1
"2"console.log("2" != true); console.log("2"? true : false); // "2" → 2 ... (2 != 1) ... 1 ← true
Expressions that use features such as post–incrementation (i++
) have an anticipated side effect. JavaScript provides short-circuit evaluation of expressions; the right operand is only executed if the left operand does not suffice to determine the value of the expression.
In early versions of JavaScript and JScript, the binary logical operators returned a Boolean value (like most C-derived programming languages). However, all contemporary implementations return one of their operands instead:
Programmers who are more familiar with the behavior in C might find this feature surprising, but it allows for a more concise expression of patterns like null coalescing:
??= | Nullish assignment | ||||||||||||||||||||||||||||||||||||||||
<nowiki>||=</nowiki> | Logical Or assignment|-| align="center" | &&= | Logical And assignment|}BitwiseJavaScript supports the following binary bitwise operators:
Examples: JavaScript supports the following unary bitwise operator:
Bitwise AssignmentJavaScript supports the following binary assignment operators:
Examples: String
Examples: const str2 = "2" + 2; // "22", not "4" or 4. ??Control structuresCompound statementsA pair of curly brackets If ... elseConditional (ternary) operatorThe conditional operator creates an expression that evaluates as one of two expressions depending on a condition. This is similar to the if statement that selects one of two statements to execute depending on a condition. I.e., the conditional operator is to expressions what if is to statements. is the same as: Unlike the if statement, the conditional operator cannot omit its "else-branch". Switch statementSee main article: Switch statement. The syntax of the JavaScript switch statement is as follows:
For loopThe syntax of the JavaScript for loop is as follows: or For ... in loopThe syntax of the JavaScript
While loopThe syntax of the JavaScript while loop is as follows: Do ... while loopThe syntax of the JavaScript WithThe with statement adds all of the given object's properties and methods into the following block's scope, letting them be referenced as if they were local variables.
The semantics are similar to the with statement of Pascal. Because the availability of with statements hinders program performance and is believed to reduce code clarity (since any given variable could actually be a property from an enclosing), this statement is not allowed in strict mode. LabelsJavaScript supports nested labels in most implementations. Loops or blocks can be labelled for the break statement, and loops for FunctionsSee main article: Function (computer programming). A function is a block with a (possibly empty) parameter list that is normally given a name. A function may use local variables. If you exit the function without a return statement, the value is returned. //In the absence of parentheses following the identifier 'gcd' on the RHS of the assignment below,//'gcd' returns a reference to the function itself without invoking it.let mygcd = gcd; // mygcd and gcd reference the same function.console.log(mygcd(60, 40)); // 20 Functions are first class objects and may be assigned to other variables. The number of arguments given when calling a function may not necessarily correspond to the number of arguments in the function definition; a named argument in the definition that does not have a matching argument in the call will have the value (that can be implicitly cast to false). Within the function, the arguments may also be accessed through the object; this provides access to all arguments using indices (e.g.), including those beyond the number of named arguments. (While the arguments list has a Primitive values (number, boolean, string) are passed by value. For objects, it is the reference to the object that is passed. Functions can be declared inside other functions, and access the outer function's local variables. Furthermore, they implement full closures by remembering the outer function's local variables even after the outer function has exited. Async/awaitObjectsFor convenience, types are normally subdivided into primitives and objects. Objects are entities that have an identity (they are only equal to themselves) and that map property names to values ("slots" in prototype-based programming terminology). Objects may be thought of as associative arrays or hashes, and are often implemented using these data structures. However, objects have additional features, such as a prototype chain, which ordinary associative arrays do not have. JavaScript has several kinds of built-in objects, namely Creating objectsObjects can be created using a constructor or an object literal. The constructor can use either a built-in Object function or a custom function. It is a convention that constructor functions are given a name that starts with a capital letter: // Object literalconst objectA = ;const objectA2 = ; // A != A2, s create new objects as copies.const objectB = ; // Custom constructor (see below) Object literals and array literals allow one to easily create flexible data structures: MethodsA method is simply a function that has been assigned to a property name of an object. Unlike many object-oriented languages, there is no distinction between a function definition and a method definition in object-related JavaScript. Rather, the distinction occurs during function calling; a function can be called as a method. When called as a method, the standard local variable is just automatically set to the object instance to the left of the "". (There are also and methods that can set explicitly—some packages such as jQuery do unusual things with .) In the example below, Foo is being used as a constructor. There is nothing special about a constructor - it is just a plain function that initialises an object. When used with the keyword, as is the norm, is set to a newly created blank object. Note that in the example below, Foo is simply assigning values to slots, some of which are functions. Thus it can assign different functions to different instances. There is no prototyping in this example. function Foo(yz) const foo1 = new Foo(1);const foo2 = new Foo(0);foo2.prefix = "b-"; console.log("foo1/2 " + foo1.pyz + foo2.pyz);// foo1/2 a-Y b-Z foo1.m3 = px; // Assigns the function itself, not its evaluated result, i.e. not pxconst baz = ;baz.m4 = px; // No need for a constructor to make an object. console.log("m1/m3/m4 " + foo1.m1 + foo1.m3 + baz.m4);// m1/m3/m4 a-X a-X c-X foo1.m2; // Throws an exception, because foo1.m2 doesn't exist. ConstructorsConstructor functions simply assign values to slots of a newly created object. The values may be data or other functions. Example: Manipulating an object: MyObject.staticC = "blue"; // On MyObject Function, not objectconsole.log(MyObject.staticC); // blue const object = new MyObject('red', 1000); console.log(object.attributeA); // redconsole.log(object.attributeB); // 1000 console.log(object.staticC); // undefinedobject.attributeC = new Date; // add a new property delete object.attributeB; // remove a property of objectconsole.log(object.attributeB); // undefined The constructor itself is referenced in the object's prototype's constructor slot. So, y.constructor; // truex instanceof Foo; // truey instanceof Foo; // false// y's prototype is Object.prototype, not// Foo.prototype, since it was initialised with// instead of new Foo.// Even though Foo is set to y's constructor slot,// this is ignored by instanceof - only y's prototype's// constructor slot is considered.Functions are objects themselves, which can be used to produce an effect similar to "static properties" (using C++/Java terminology) as shown below. (The function object also has a special Object deletion is rarely used as the scripting engine will garbage collect objects that are no longer being referenced. InheritanceJavaScript supports inheritance hierarchies through prototyping in the manner of Self. In the following example, the class inherits from the class.When is created as, the reference to the base instance of is copied to . Derive does not contain a value for, so it is retrieved from when is accessed. This is made clear by changing the value of, which is reflected in the value of . Some implementations allow the prototype to be accessed or set explicitly using the slot as shown below. function Derived const base = new Base;Derived.prototype = base; // Must be before new DerivedDerived.prototype.constructor = Derived; // Required to make `instanceof` work const d = new Derived; // Copies Derived.prototype to d instance's hidden prototype slot.d instanceof Derived; // trued instanceof Base; // true base.aBaseFunction = function ; d.anOverride; // Derived::anOverrided.aBaseFunction; // Base::aNEWBaseFunctionconsole.log(d.aBaseFunction Derived.prototype.aBaseFunction); // trueconsole.log(d.__proto__ base); // true in Mozilla-based implementations and false in many others.The following shows clearly how references to prototypes are copied on instance creation, but that changes to a prototype can affect all instances that refer to it. function Base Base.prototype.m = m2;const bar = new Base;console.log("bar.m " + bar.m); // bar.m Two function Top const t = new Top; const foo = new Base;Base.prototype = t;// No effect on foo, the *reference* to t is copied.console.log("foo.m " + foo.m); // foo.m Two const baz = new Base;console.log("baz.m " + baz.m); // baz.m Three t.m = m1; // Does affect baz, and any other derived classes.console.log("baz.m1 " + baz.m); // baz.m1 One In practice many variations of these themes are used, and it can be both powerful and confusing. Exception handlingJavaScript includes a The Initially, the statements within the try block execute. If an exception is thrown, the script's control flow immediately transfers to the statements in the catch block, with the exception available as the error argument. Otherwise the catch block is skipped. The catch block can, if it does not want to handle a specific error. In any case the statements in the finally block are always executed. This can be used to free resources, although memory is automatically garbage collected. Either the catch or the finally clause may be omitted. The catch argument is required. The Mozilla implementation allows for multiple catch statements, as an extension to the ECMAScript standard. They follow a syntax similar to that used in Java: "InvalidNameException") catch (e if e"InvalidIdException") catch (e if e "InvalidEmailException") catch (e)In a browser, the event is more commonly used to trap exceptions. Native functions and methodseval (expression)Evaluates the first parameter as an expression, which can include assignment statements. Variables local to functions can be referenced by the expression. However, represents a major security risk, as it allows a bad actor to execute arbitrary code, so its use is discouraged.[15] See alsoFurther reading
External links
|