JavaScript syntax
The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.
The examples below make use of the
console.log function present in most browsers for standard text output.The JavaScript standard library lacks an official standard text output function. 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.TypeScript, which extends JavaScript with type annotations and additional features, has the same syntax as well as its own additional features.
Origins
Brendan Eich summarized the ancestry of the syntax in the first paragraph of the JavaScript 1.1 specification as follows:JavaScript syntax is mostly derived from Java syntax, which in turn is derived from C syntax and C++ syntax.
Basics
Keywords
Keywords
The following words are keywords and cannot be used as identifiers under any circumstances.arguments, async, await, assert, break, case, catch, class, const, continue, debugger, default, delete, do, else, enum, eval, export, extends, finally, for, function, if, implements, import, in, instanceof, interface, let, new, package, private, protected, public, return, static, super, switch, this, throw, try, typeof, using, var, void, while, with, yieldReserved words for literal values
The following words refer to literal values used by the language.true, false, nullJavaScript also defines the following global constants, which are not keywords.
NaN, Infinity, undefined, globalThisRemoved keywords
The following words, primarily associated with Java, were removed from the ECMAScript 5/6 standard:abstract, boolean, byte, char, double, final, float, goto, int, long, native, short, synchronized, throws, transient, volatileTypeScript keywords
The following words are keywords exclusive to TypeScript.abstract, any, as, declare, infer, keyof, module, namespace, never, readonly, type, unknownCase sensitivity
JavaScript is case sensitive. It is common to start the name of a constructor with a capitalized letter, and the name of a function or variable with a lower-case letter.Example:
var a = 5;
console.log; // 5
console.log; // throws a ReferenceError: A is not defined
Whitespace and semicolons
Unlike in C, whitespace in JavaScript source can directly impact semantics. Semicolons end statements in JavaScript. Because of automatic semicolon insertion, some statements that are well formed when a newline is parsed will be considered complete, as if a semicolon were inserted just prior to the newline. Some authorities advise supplying statement-terminating semicolons explicitly, because it may lessen unintended effects of the automatic semicolon insertion.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 "
.foo
// Treated as:
// a = b + c.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 '.foo
// Treated as:
// a = b + c;
// .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. In such a case where perhaps unusual semicolon placement occurs, it may just be better to manually place semicolons at the end of statements.
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.
return
a + b;
// Returns undefined. Treated as:
// return;
// a + b;
// Should be written as:
// return a + b;
Comments
Comment syntax is the same as in C++, Swift and other programming languages.
Single-line comments begin with // and continue until the end of the line. A second type of comments can also be made; these start with /* and end with */ and can be used for multi-line comments.
A third type of comment, the hashbang comment, starts with #! and continues until the end of the line. They are only valid at the start of files and are intended for use in CLI environments.
- ! Hashbang comment
// One-line comment
/* Multi-line
comment */
Variables
Variables in standard JavaScript have no type attached, so any value 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. A variable's identifier must start with a letter, underscore, or dollar sign, while subsequent characters can also be digits. JavaScript is case sensitive, so the uppercase characters "" through "" are different from the lowercase characters "" through "".
Starting with JavaScript 1.5, ISO 8859-1 or Unicode letters can be used in identifiers. 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.
Scoping and hoisting
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. This is referred to as , and it is equivalent to variables being forward declared at the top of the function or block.
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,
var func = function // declaration is hoisted only
function func // declaration and assignment are hoisted
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.
Declaration and assignment
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. As a consequence, a variable never declared will be global, if assigned. Declaring a variable in the global scope, assigning a never declared identifier or adding a property to the global object 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.
Examples
Here are some examples of variable declarations and scope:
var x1 = 0; // A global variable, because it is not in any function
let x2 = 0; // Also global, this time because it is not in any block
function f
f;
console.log; // This line will raise a ReferenceError exception, because the value of z is no longer available
for console.log;
console.log; // throws a ReferenceError: i is not defined
for console.log; // throws a TypeError: Assignment to constant variable
for console.log; //will not raise an exception. i is not reassigned but recreated in every iteration
const pi; // throws a SyntaxError: Missing initializer in const declaration
Primitive data types
The JavaScript language provides six primitive data types:Undefined, Number, BigInt, [|String], Boolean, Symbol
Some of the primitive data types also provide a set of named values that represent the extents of the type boundaries. These named values are described within the appropriate sections below.
Undefined
The value of "undefined" 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.
let test; // variable declared, but not defined,...
//... set to value of undefined
const testObj = ;
console.log; // test variable exists, but value not...
//... defined, displays undefined
console.log; // testObj exists, property does not,...
//... displays undefined
console.log; // unenforced type during check, displays true
console.log; // enforce type during check, displays false
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 will not work as expected:
function isUndefined // like this...
function isUndefined //... or that second one
function isUndefined //... or that third one
Here, calling isUndefined raises a if is an unknown identifier, whereas does not.
Number
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:
console.log; // displays false
console.log; // displays 0.9299999999999999
As a result, a routine such as the method should be used to round numbers whenever they are .
Numbers may be specified in any of these notations:
345; // an "integer", although there is only one numeric type in JavaScript
34.5; // a floating-point number
3.45e2; // another floating-point, equivalent to 345
0b1011; // a binary integer equal to 11
0o377; // an octal integer equal to 255
0xFF; // a hexadecimal integer equal to 255, digits represented by the...
//... letters A-F may be upper or lowercase
There is also a numeric separator,, introduced in ES2021:
// Note: Wikipedia syntax does not support numeric separators yet
1_000_000_000; // Used with big numbers
1_000_000.5; // Support with decimals
1_000e1_000; // Support with exponents
// Support with binary, octals and hex
0b0000_0000_0101_1011;
0o0001_3520_0237_1327;
0xFFFF_FFFF_FFFF_FFFE;
// But users cannot use them next to a non-digit number part, or at the start or end
_12; // Variable is not defined
12_; // Syntax error
12_.0; // Syntax error
12._0; // Syntax error
12e_6; // Syntax error
1000____0000; // Syntax error of the number type may be obtained by two program expressions:
Infinity; // positive infinity
NaN; // The Not-A-Number value, also returned as a failure in...
//... string-to-number conversions
Infinity and NaN are numbers:
typeof Infinity; // returns "number"
typeof NaN; // returns "number"
These three special values correspond and behave as the IEEE-754 describes them.
The Number [|constructor], or a unary + or -, may be used to perform explicit numeric conversion:
const myString = "123.456";
const myNumber1 = Number;
const myNumber2 = +myString;
When used as a constructor, a numeric wrapper object is created :
const myNumericWrapper = new Number;
However, NaN is not equal to itself:
const nan = NaN;
console.log; // false
console.log; // false
console.log; // true
console.log; // true
// Users can use the isNaN methods to check for NaN
console.log; // true
console.log; // true
console.log; // false
console.log; // true
BigInt
In JavaScript, regular numbers are represented with the IEEE 754 floating point type, meaning integers can only safely be stored if the value falls between Number.MIN_SAFE_INTEGER and Number.MAX_SAFE_INTEGER. BigInts instead represent integers of any size, allowing programmers to store integers too high or low to be represented with the IEEE 754 format.
There are two ways to declare a BigInt value. An n can be appended to an integer, or the BigInt function can be used:
const a = 12345n; // Creates a variable and stores a BigInt value of 12345
const b = BigInt;
String
A string in JavaScript is a sequence of characters. In JavaScript, strings can be created directly by placing the series of characters between double or single quotes. Such strings must be written on a single line, but may include escaped newline characters. The JavaScript standard allows the backquote character to quote multiline literal strings, as well as embedded expressions using the syntax $.
const greeting = "Hello, World!";
const anotherGreeting = 'Greetings, people of Earth.';
const aMultilineGreeting = `Warm regards,
John Doe.`
// Template literals type-coerce evaluated expressions and interpolate them into the string.
const templateLiteral = `This is what is stored in anotherGreeting: $.`;
console.log; // 'This is what is stored in anotherGreeting: 'Greetings, people of Earth.''
console.log;
Individual characters within a string can be accessed using the method. This is the preferred way when accessing individual characters within a string, because it also works in non-modern browsers:
const h = greeting.charAt;
In modern browsers, individual characters within a string can be accessed through the same notation as arrays:
const h = greeting;
However, JavaScript strings are immutable:
greeting = "H"; // Fails.
Applying the equality operator to two strings returns true, if the strings have the same contents, which means: of the same length and containing the same sequence of characters. Thus:
const x = "World";
const compare1 = ; // Here compare1 contains true.
const compare2 = ; // 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.
let x = '"Hello, World!" he said.'; // Just fine.
x = ""Hello, World!" he said."; // Not good.
x = "\"Hello, World!\" he said."; // Works by escaping " with \"
The constructor creates a string object :
const greeting = new String;
These objects have a method returning the primitive string wrapped within them:
const s = new String;
typeof s; // Is 'object'.
typeof s.valueOf; // Is 'string'.
Equality between two objects does not behave as with string primitives:
const s1 = new String;
const s2 = new String;
s1 s2; // Is false, because they are two distinct objects.
s1.valueOf s2.valueOf; // Is true.
Boolean
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 evaluate as, including the strings, and any object.
Type conversion
Automatic type coercion by the equality comparison operators can be avoided by using the type checked comparison operators.
When type conversion is required, JavaScript converts,,, or operands as follows:
;: The string is converted to a number value. JavaScript attempts to convert the string numeric literal to a Number type value. First, a mathematical value is derived from the string numeric literal. Next, this value is rounded to nearest Number type value.
;: If one of the operands is a Boolean, the Boolean operand is converted to 1 if it is, or to 0 if it is.
;: If an object is compared with a number or string, JavaScript attempts to return the default value for the object. An object is converted to a primitive String or Number value, using the or methods of the object. If this fails, a runtime error is generated.
Boolean type conversion
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.
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:, or, in the case of disjunction: ; otherwise the right–operand is returned. Automatic type coercion by the comparison operators may differ for cases of mixed Boolean and number-compatible operands, 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:.
// Automatic type coercion
console.log; // false... true → 1 ! 2 ← 2
console.log; // false... false → 0 ! 2 ← 2
console.log; // true.... true → 1 1 ← 1
console.log; // true.... false → 0 0 ← 0
console.log; // false... true → 1 ! 2 ← "2"
console.log; // false... false → 0 ! 2 ← "2"
console.log; // true.... true → 1 1 ← "1"
console.log; // true.... false → 0 0 ← "0"
console.log; // true.... false → 0 0 ← ""
console.log; // false... false → 0 ! NaN
console.log; // false...... NaN is not equivalent to anything, including NaN.
// Type checked comparison
console.log; // false...... data types do not match
// Explicit type coercion
console.log; // true.... data types and values match
console.log; // false... data types match, but values differ
console.log; // true.... only ±0 and NaN are "falsy" numbers
console.log; // true.... only the empty string is "falsy"
console.log); // 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 be used in preference to the Boolean object.
const b = new Boolean; // Object false
const t = Boolean; // Boolean true
const f = Boolean); // Boolean false
let n = new Boolean; // Not recommended
n = new Boolean); // Preferred
if || !new Boolean || !t) else if
Symbol
Symbols are a feature introduced in ES6. Each symbol is guaranteed to be a unique value, and they can be used for encapsulation.
Example:
let x = Symbol;
const y = Symbol;
x y; // => false
const symbolObject = ;
const normalObject = ;
// since x and y are unique,
// they can be used as unique keys in an object
symbolObject = 1;
symbolObject = 2;
symbolObject; // => 1
symbolObject; // => 2
// as compared to normal numeric keys
normalObject = 1;
normalObject = 2; // overrides the value of 1
normalObject; // => 2
// changing the value of x does not change the key stored in the object
x = Symbol;
symbolObject; // => undefined
// changing x back just creates another unique Symbol
x = Symbol;
symbolObject; // => undefined
There are also well known symbols.
One of which is Symbol.iterator; if something implements Symbol.iterator, it is iterable:
const x = ; // x is an Array
x Array.prototype; // and Arrays are iterable
const xIterator = x; // The function should provide an iterator for x
xIterator.next; //
xIterator.next; //
xIterator.next; //
xIterator.next; //
xIterator.next; //
xIterator.next; //
// for..of loops automatically iterate values
for
// Sets are also iterable:
in Set.prototype; // true
for
Native objects
The JavaScript language provides a handful of native objects. JavaScript native objects are considered part of the JavaScript specification. JavaScript environment notwithstanding, this set of objects should always be available.
Array
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.
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.
const myArray = ; // Point the variable myArray to a newly...
//... created, empty Array
myArray.push; // Fill the next empty index, in this case 0
console.log; // Equivalent to console.log;
Arrays have a length property that is guaranteed to always be larger than the largest integer index used in the array. It is automatically updated, if one creates a property with an even larger index. Writing a smaller number to the length property will remove larger indices.
Elements of Arrays may be accessed using normal object property access notation:
myArray; // the 2nd item in myArray
myArray;
The above two are equivalent. It is not possible to use the "dot"-notation or strings with alternative representations of the number:
myArray.1; // syntax error
myArray; // not the same as myArray
Declaration of an array can use either an Array literal or the Array constructor:
let myArray;
// Array literals
myArray = ; // length of 2
myArray = ; // same array - Users can also have an extra comma at the end
// It is also possible to not fill in parts of the array
myArray = ; // length of 6
myArray = ; // same array
myArray = ; // length of 7
// With the constructor
myArray = new Array; // length of 6
myArray = new Array; // 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 2.
One can use the object declaration literal to create objects that behave much like associative arrays in other languages:
const dog = ;
dog; // results in "brown"
dog.color; // also results in "brown"
One can use the object and array declaration literals to quickly create arrays that are associative, multidimensional, or both.
const cats = ;
cats; // results in "large"
const dogs = ;
dogs; // results in "small"
dogs.rover.color; // results in "brown"
Date
A Date object stores a signed millisecond count with zero representing 1970-01-01 00:00:00 UT and a range of ±108 days. There are several ways of providing arguments to the Date constructor. Note that months are zero-based.
new Date; // create a new Date instance representing the current time/date.
new Date; // create a new Date instance representing 2010-Mar-01 00:00:00
new Date; // create a new Date instance representing 2010-Mar-01 14:25:30
new Date; // create a new Date instance from a String.
Methods to extract fields are provided, as well as a useful toString:
const d = new Date; // 2010-Mar-01 14:25:30;
// Displays '2010-3-1 14:25:30':
console.log + '-' + + '-' + d.getDate + ' '
+ d.getHours + ':' + d.getMinutes + ':' + d.getSeconds);
// Built-in toString returns something like 'Mon 1 March, 2010 14:25:30 GMT-0500 ':
console.log;
Error
Custom error messages can be created using the Error class:
throw new Error;
These can be caught by try...catch...finally blocks as described in the section on exception handling.
Math
The object contains various math-related constants and functions. 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 [Pi|]: 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 = Whole circle arctangent 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 : gives xy e.g. 0.17068 Pseudorandom number between 0 and 1 2 Round to the nearest integer; half fractions are rounded up 0.70711 Sine 7 Square root 1 Tangent
Regular expression
/expression/.test; // returns Boolean
"string".search; // returns position Number
"string".replace;
// Here are some examples
if console.log;
console.log; // 11
console.log; // "My name is John"
Character classes
// \d - digit
// \D - non digit
// \s - space
// \S - non space
// \w - word char
// \W - non word
// - one of
// - one not of
// - - range
if console.log;
if console.log;
if console.log;
if console.log;
if console.log;
if console.log;
Character matching
// A...Z a...z 0...9 - alphanumeric
// \u0000...\uFFFF - Unicode hexadecimal
// \x00...\xFF - ASCII hexadecimal
// \t - tab
// \n - new line
// \r - CR
//. - any character
// | - OR
if console.log ;
if console.log ;
Repeaters
// ? - 0 or 1 match
// * - 0 or more
// + - 1 or more
// - exactly n
// - n or more
// - n or less
// - range n to m
if console.log; // match: "ac", "abc"
if console.log; // match: "ac", "abc", "abbc", "abbbc" etc.
if console.log; // match: "abc", "abbc", "abbbc" etc.
if console.log; // match: "abbbc"
if console.log; // match: "abbbc", "abbbbc", "abbbbbc" etc.
if console.log; // match: "abc", "abbc", "abbbc"
Anchors
// ^ - string starts with
// $ - string ends with
if console.log ;
if console.log ;
Subexpression
// - groups characters
if ?/.test) console.log; // match: "water", "watermark",
if |/.test) console.log;
Flags
// /g - global
// /i - ignore upper/lower case
// /m - allow matches to span multiple lines
console.log; // "hi John!"
console.log; // "ratutam"
console.log; // "ratutum"
Advanced methods
my_array = my_string.split;
// example
my_array = "dog,cat,cow".split; // my_array;
my_array = my_string.match;
// example
my_array = "We start at 11:30, 12:15 and 16:45".match; // my_array;
Capturing groups
const myRe = / /;
const results = myRe.exec;
if else console.log;
Function
Every function in JavaScript is an instance of the Function constructor:
// x, y is the argument. 'return x + y' is the function body, which is the last in the argument list.
const add = new Function;
add; // => 3
The add function above may also be defined using a function expression:
const add = function ;
add; // => 3
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.
const add = => ;
// values can also be implicitly returned
const addImplicit = => x + y;
add; // => 3
addImplicit // => 3
For functions that need to be hoisted, there is a separate expression:
function add
add; // => 3
Hoisting allows users to use the function before it is "declared":
add; // => 3, not a ReferenceError
function add
A function instance has properties and methods.
function subtract
console.log; // => 2, arity of the function
console.log);
/*
"function subtract "
- /
Operators
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.
// Concatenate 2 strings
console.log; // displays Hello
// Add two numbers
console.log; // displays 8
// Adding a number and a string results in concatenation
console.log; // displays 22
console.log; // displays $34, but $7 may have been expected
console.log; // displays $7
console.log; // displays 77, numbers stay numbers until a string is added
// Convert a string to a number using the unary plus
console.log; // displays true
console.log; // displays NaN
Similarly, the '*' operator is overloaded: it can convert a string into a number.
console.log; // displays 8
console.log; // 21
console.log; // 21
console.log; // displays NaN
Arithmetic
JavaScript supports the following binary arithmetic operators:
+addition -subtraction *multiplication /division %modulo **exponentiation
JavaScript supports the following unary arithmetic operators:
+unary conversion of string to number -unary negation ++increment --decrement
let x = 1;
console.log; // x becomes 2; displays 2
console.log; // displays 2; x becomes 3
console.log; // x is 3; displays 3
console.log; // displays 3; x becomes 2
console.log; // displays 2; x is 2
console.log; // x becomes 1; displays 1
The modulo operator displays the remainder after division by the modulus. If negative numbers are involved, the returned value depends on the operand.
const x = 17;
console.log; // displays 2
console.log; // displays 5
console.log; // displays -2
console.log; // displays -2
console.log; // displays 2
To always return a non-negative number, users can re-add the modulus and apply the modulo operator again:
const x = 17;
console.log; // displays 3
Users could also do:
const x = 17;
console.log; // also 3
Assignment
Assignment of primitive types
let x = 9;
x += 1;
console.log; // displays: 10
x *= 30;
console.log; // displays: 300
x /= 6;
console.log; // displays: 50
x -= 3;
console.log; // displays: 47
x %= 7;
console.log; // displays: 5
Assignment of object types
/**
* To learn JavaScript objects...
*/
const object_1 = ; // assign reference of newly created object to object_1
let object_2 = ;
let object_3 = object_2; // object_3 references the same object as object_2 does
object_3.a = 2;
message; // displays 1 2 2
object_2 = object_1; // object_2 now references the same object as object_1
// object_3 still references what object_2 referenced before
message; // displays 1 1 2
object_2.a = 7; // modifies object_1
message; // displays 7 7 2
object_3.a = 5; // object_3 does not change object_2
message; // displays 7 7 5
object_3 = object_2;
object_3.a=4; // object_3 changes object_1 and object_2
message; // displays 4 4 4
/**
* Prints the console.log message
*/
function message
Destructuring assignment
In Mozilla's JavaScript, since version 1.7, destructuring assignment allows the assignment of parts of data structures to several variables at once. The left hand side of an assignment is a pattern that resembles an arbitrarily nested object/array literal containing l-lvalues at its leaves that are to receive the substructures of the assigned value.
let a, b, c, d, e;
= ;
console.log; // displays: 3,4,5
e = ;
const arr = ;
;
console.log; // displays: 5,6,Baz,,,Content
= ; // swap contents of a and b
console.log; // displays: 6,5
= ; // permutations
= ;
console.log; // displays: 4,5,3
Spread/rest operator
The ECMAScript 2015 standard introduced the "..." array operator, for the related concepts of "spread syntax" and "rest parameters". 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 "" into ", foo, foo;
// It can be used multiple times in the same expression
const b = ; // b = ;
// It can be combined with non-spread items.
const c = ; // c = ;
// For comparison, doing this without the spread operator
// creates a nested array.
const d = ; // d = 1, 2, 3, 4],
foo; // "0" → c =
Rest parameters are similar to Javascript's arguments object, which is an array-like object that contains all of the parameters 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.
Comparison
Variables referencing objects are equal or identical only if they reference the same object:
const obj1 = ;
const obj2 = ;
const obj3 = obj1;
console.log; //false
console.log; //true
console.log; //true
See also String.
Logical
JavaScript provides four logical operators:
- unary negation
- binary disjunction and conjunction
- ternary conditional
In the context of a logical operation, any expression evaluates to true except the following:
- Strings:
"", '' , - Numbers:
0, -0, NaN, - Special:
null, undefined, - Boolean:
false.
The Boolean function can be used to explicitly convert to a primitive of type Boolean:
// Only empty strings return false
console.log;
console.log;
console.log;
// Only zero and NaN return false
console.log;
console.log;
console.log; // equivalent to -1*0
console.log;
// All objects return true
console.log;
console.log;
console.log;
// These types return false
console.log;
console.log; // 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:
console.log;
console.log;
console.log;
console.log;
console.log;
console.log;
console.log;
console.log;
console.log;
console.log;
console.log;
console.log;
The ternary operator can also be used for explicit conversion:
console.log; console.log; // “truthy”, but the comparison uses .toString
console.log; console.log; // .toString "0"
console.log; console.log; // "0" → 0... ... 0 ← false
console.log; console.log; // .toString "1"
console.log; console.log; // "1" → 1... ... 1 ← true
console.log; console.log; // .toString "2"
console.log; console.log; // "2" → 2... ... 1 ← true
Expressions that use features such as post–incrementation 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.
console.log; // When a is true, there is no reason to evaluate b.
console.log; // When a is false, there is no reason to evaluate b.
console.log; // When c is true, there is no reason to evaluate f.
In early versions of JavaScript and JScript, the binary logical operators returned a Boolean value. However, all contemporary implementations return one of their operands instead:
console.log; // if a is true, return a, otherwise return b
console.log; // if a is false, return a, otherwise return b
Programmers who are more familiar with the behavior in C might find this feature surprising, but it allows for a more concise expression of patterns like null coalescing:
const s = t || ""; // assigns t, or the default value, if t is null, empty, etc.
Bitwise
JavaScript supports the following binary bitwise operators:
&AND |OR ^XOR !NOT <<shift left >>shift right ; copies of the
leftmost bit are shifted in from the left >>>shift right. For positive numbers,
>> and >>> yield the same result.
Examples:
const x = 11 & 6;
console.log; // 2
JavaScript supports the following unary bitwise operator:
Bitwise Assignment
JavaScript supports the following binary assignment operators:
&=and |=or ^=xor <<=shift left >>=shift right ; copies of the
leftmost bit are shifted in from the left >>>=shift right. For positive numbers,
>>= and >>>= yield the same result.
Examples:
let x=7;
console.log; // 7
x<<=3;
console.log; // 7->14->28->56
String
=assignment +concatenation +=concatenate and assign
Examples:
let str = "ab" + "cd"; // "abcd"
str += "e"; // "abcde"
const str2 = "2" + 2; // "22", not "4" or 4.
Control structures
Compound statements
A pair of curly brackets and an enclosed sequence of statements constitute a compound statement, which can be used wherever a statement can be used.
If ... else
if else if else
Conditional (ternary) operator
The conditional operator creates an expression that evaluates as one of two expressions depending on a condition. This is similar to the if statement that selects one of two statements to execute depending on a condition. I.e., the conditional operator is to expressions what if is to statements.
const result = condition ? expression : alternative;
is the same as:
if else
Unlike the if statement, the conditional operator cannot omit its "else-branch".
Switch statement
The syntax of the JavaScript switch statement is as follows:
switch
break; is optional; however, it is usually needed, since otherwise code execution will continue to the body of the next case block. This fall through behavior can be used when the same set of statements apply in several cases, effectively creating a disjunction between those cases.
- Add a break statement to the end of the last case as a precautionary measure, in case additional cases are added later.
- String literal values can also be used for the case values.
- Expressions can be used instead of values.
- The default case is executed when the expression does not match any other specified cases.
- Braces are required.
For loop
The syntax of the JavaScript for loop is as follows:
for
or
for // one statement
For ... in loop
The syntax of the JavaScript for... in loop is as follows:
for
- Iterates through all enumerable properties of an object.
- Iterates through all used indices of array including all user-defined properties of array object, if any. Thus it may be better to use a traditional for loop with a numeric index when iterating over arrays.
- There are differences between the various Web browsers with regard to which properties will be reflected with the for...in loop statement. In theory, this is controlled by an internal state property defined by the ECMAscript standard called "DontEnum", but in practice, each browser returns a slightly different set of properties during introspection. It is useful to test for a given property using. Thus, adding a method to the array prototype with may cause
for... in loops to loop over the method's name.
While loop
The syntax of the JavaScript while loop is as follows:
while
Do ... while loop
The syntax of the JavaScript do... while loop is as follows:
do while ;
With
The 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.
with ;
- Note the absence of before each invocation.
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, this statement is not allowed in strict mode.
Labels
JavaScript supports nested labels in most implementations. Loops or blocks can be labeled for the break statement, and loops for continue. Although goto is a reserved word, goto is not implemented in JavaScript.
loop1: for //end of loop1
block1:
goto block1; // Parse error.
Functions
A function is a block with a parameter list that is normally given a name. A function may use local variables. If a user exits the function without a return statement, the value is returned.
function gcd
console.log; // 20
//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; // 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 . Within the function, the arguments may also be accessed through the object; this provides access to all arguments using indices, including those beyond the number of named arguments.
function add7 ;
add7; // 11
add7; // 9
Primitive values are passed by value. For objects, it is the reference to the object that is passed.
const obj1 = ;
const obj2 = ;
function foo
foo; // Does not affect obj1 at all. 3 is additional parameter
console.log; // writes 1 3
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.
let t = "Top";
let bar, baz;
function foo
foo;
baz;
bar; // "baz arg" even though foo has exited.
console.log; // Top
An anonymous function is simply a function without a name and can be written either using function or arrow notation. In these equivalent examples an anonymous function is passed to the map function and is applied to each of the elements of the array.
.map
Objects
For convenience, types are normally subdivided into primitives and objects. Objects are entities that have an identity and that map property names to values. Objects may be thought of as associative arrays or hashes, and are often implemented using these data structures. However, objects have additional features, such as a prototype chain, which ordinary associative arrays do not have.
JavaScript has several kinds of built-in objects, namely Array, Boolean, Date, Function, Math, Number, Object, RegExp and String. Other objects are "host objects", defined not by the language, but by the runtime environment. For example, in a browser, typical host objects belong to the DOM.
Creating objects
Objects can be created using a constructor or an object literal. The constructor can use either a built-in Object function or a custom function. It is a convention that constructor functions are given a name that starts with a capital letter:
// Constructor
const anObject = new Object;
// Object literal
const objectA = ;
const objectA2 = ; // A != A2, s create new objects as copies.
const objectB = ;
// Custom constructor
Object literals and array literals allow one to easily create flexible data structures:
const myStructure = ;
This is the basis for JSON, which is a simple notation that uses JavaScript-like syntax for data exchange.
Methods
A 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 "".
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 initializes 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 px
function Foo
const foo1 = new Foo;
const foo2 = new Foo;
foo2.prefix = "b-";
console.log + foo2.pyz);
// foo1/2 a-Y b-Z
foo1.m3 = px; // Assigns the function itself, not its evaluated result, i.e. not px
const baz = ;
baz.m4 = px; // No need for a constructor to make an object.
console.log + foo1.m3 + baz.m4);
// m1/m3/m4 a-X a-X c-X
foo1.m2; // Throws an exception, because foo1.m2 does not exist.
Constructors
Constructor functions simply assign values to slots of a newly created object. The values may be data or other functions.
Example: Manipulating an object:
function MyObject
MyObject.staticC = "blue"; // On MyObject Function, not object
console.log; // blue
const object = new MyObject;
console.log; // red
console.log; // 1000
console.log; // undefined
object.attributeC = new Date; // add a new property
delete object.attributeB; // remove a property of object
// note that unlike C++, delete does not invoke a "destructor",
// but rather removes a property of an object.
console.log; // undefined
The constructor itself is referenced in the object's prototype's constructor slot. So,
function Foo
// Use of 'new' sets prototype slots would set x's prototype to Foo.prototype,
// and Foo.prototype has a constructor slot pointing back to Foo).
const x = new Foo;
// The above is almost equivalent to
const y = ;
y.constructor = Foo;
y.constructor;
// Except
x.constructor y.constructor; // true
x instanceof Foo; // true
y instanceof Foo; // false
// y's prototype is Object.prototype, not
// Foo.prototype, since it was initialized 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" as shown below.
Object deletion is rarely used as the scripting engine will garbage collect objects that are no longer being referenced.
Inheritance
JavaScript 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 Base
function Derived
const base = new Base;
Derived.prototype = base; // Must be before new Derived
Derived.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; // true
d instanceof Base; // true
base.aBaseFunction = function ;
d.anOverride; // Derived::anOverride
d.aBaseFunction; // Base::aNEWBaseFunction
console.log; // true
console.log; // 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 m1
function m2
function m3
function Base
Base.prototype.m = m2;
const bar = new Base;
console.log); // 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 Two
const baz = new Base;
console.log); // baz.m Three
t.m = m1; // Does affect baz, and any other derived classes.
console.log); // baz.m1 One
In practice many variations of these themes are used, and it can be both powerful and confusing.
Exception handling
JavaScript includes a try... catch... finally exception handling statement to handle run-time errors.
The try... catch... finally statement catches exceptions resulting from an error or a throw statement. Its syntax is as follows:
try catch finally
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. Although memory is automatically garbage collected, this can be used to manually perform cleanup of resources.
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:
try catch catch catch catch finally
In a browser, the event is more commonly used to trap exceptions.
onerror = function ;
Native functions and methods
eval (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.
> ;
val 9
undefined
TypeScript-specific features
TypeScript, a superset of JavaScript developed by Microsoft, adds the following syntax extensions to JavaScript:
- Type signatures and compile-time type checking
- Type inference
- Interfaces
- Enumerated types
- Generics
- Namespaces
- Tuples
- Explicit resource management
Syntactically, TypeScript is very similar to JScript.NET, another Microsoft implementation of the ECMA-262 language standard that added support for static typing and classical object-oriented language features such as classes, inheritance, interfaces, and namespaces. Other inspirations include Java and C#.
Type annotations
TypeScript provides static typing through type annotations to enable type checking at compile time.
function add: number
Primitive types are annotated using all-lowercase types, such as number, boolean, bigint, and string. These types are distinct from their boxed counterparts, which cannot have operations performed from values directly. There are additionally undefined and null types for their respective values.
All other non-primitive types are annotated using their class name, such as Error. Arrays can be written in two different ways which are both syntactically the same: the generic-based syntax Array and a shorthand with T.
Additional built-in data types are tuples, unions, never, unknown, void, and any:
- An array with predefined data types at each index is a tuple, represented as
. - A variable that can hold more than one type of data is a union, represented using the logical OR
| symbol. - The
never type is used when a given type should be impossible to create, which is useful for filtering mapped types. - The
unknown type is used when dealing with data of an unpredictable shape. Unlike any, an unknown-typed variable will throw compilation errors when attempting to access properties or methods on that variable without first narrowing the type to something known. This type is often used for catching Errors, handling API responses, or user input. - The
void type is used to represent the lack of a type, e.g. from a function with no return statement. - A value of type
any supports the same operations as a value in JavaScript and minimal static type checking is performed, which makes it suitable for weakly or dynamically typed structures. This is generally discouraged practice and should be avoided when possible.
Type annotations can be exported to a separate declarations file to make type information available for TypeScript scripts using types already compiled into JavaScript. Annotations can be declared for an existing JavaScript library, as has been done for Node.js and jQuery.
The TypeScript compiler makes use of type inference when types are not given. For example, the add method in the code above would be inferred as returning a number even if no return type annotation had been provided. This is based on the static types of left and right being numbers, and the compiler's knowledge that the result of adding two numbers is always a number.
If no type can be inferred because of lack of declarations, then it defaults to the dynamic any type. Additional module types can be provided using a.d.ts declaration file using the declare module "moduleName" syntax.
Declaration files
When a TypeScript script gets compiled, there is an option to generate a declaration file that functions as an interface to the components in the compiled JavaScript. In the process, the compiler strips away all function and method bodies and preserves only the signatures of the types that are exported. The resulting declaration file can then be used to describe the exported virtual TypeScript types of a JavaScript library or module when a third-party developer consumes it from TypeScript.
The concept of declaration files is analogous to the concept of header files found in C/C++.
declare namespace Arithmetics
Type declaration files can be written by hand for existing JavaScript libraries, as has been done for jQuery and Node.js.
Large collections of declaration files for popular JavaScript libraries are hosted on GitHub in .
Generics
TypeScript supports generic programming using a syntax similar to Java. The following is an example of the identity function.
function identity: T
Similar to Java generics, it is possible to bound a type parameter:
function f: void
function prop: T
Also, like C++, it is possible to have default generics parameters.
function makeArray: T
Classes
TypeScript uses the same annotation style for class methods and fields as for functions and variables respectively. Compared with vanilla JavaScript classes, a TypeScript class can also implement an interface through the implements keyword, use generic parameters similarly to Java, and specify public and private fields.
class Person
Modules and namespaces
TypeScript distinguishes between modules and namespaces, similar to C++ modules. Both features in TypeScript support encapsulation of classes, interfaces, functions and variables into containers. Namespaces use JavaScript immediately-invoked function expressions to encapsulate code, whereas modules use existing JavaScript library patterns.
Resource management
Although TypeScript does not have manual memory management, it has resource management similar to using-with-resource blocks in C# or try-with-resources blocks in Java, or C++ resource acquisition is initialization, that automatically close resources without need for finally blocks. In TypeScript, to automatically close an object, it must implement a global interface Disposable, and implement a method Symbol.dispose. This will automatically be called at the end of scope.
import * as fs from 'fs';
class TempFile implements Disposable
export function doSomeWork