repo_id
stringlengths 22
103
| file_path
stringlengths 41
147
| content
stringlengths 181
193k
| __index_level_0__
int64 0
0
|
---|---|---|---|
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/property_access_denied/index.md | ---
title: 'Error: Permission denied to access property "x"'
slug: Web/JavaScript/Reference/Errors/Property_access_denied
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "Permission denied to access property" occurs when there was
an attempt to access an object for which you have no permission.
## Message
```plain
DOMException: Blocked a frame with origin "x" from accessing a cross-origin frame. (Chromium-based)
DOMException: Permission denied to access property "x" on cross-origin object (Firefox)
SecurityError: Blocked a frame with origin "x" from accessing a cross-origin frame. Protocols, domains, and ports must match. (Safari)
```
## Error type
{{domxref("DOMException")}}.
## What went wrong?
There was attempt to access an object for which you have no permission. This is likely
an {{HTMLElement("iframe")}} element loaded from a different domain for which you
violated the [same-origin policy](/en-US/docs/Web/Security/Same-origin_policy).
## Examples
### No permission to access document
```html
<!doctype html>
<html lang="en-US">
<head>
<iframe
id="myframe"
src="http://www1.w3c-test.org/common/blank.html"></iframe>
<script>
onload = function () {
console.log(frames[0].document);
// Error: Permission denied to access property "document"
};
</script>
</head>
<body></body>
</html>
```
## See also
- {{HTMLElement("iframe")}}
- [Same-origin policy](/en-US/docs/Web/Security/Same-origin_policy)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/deprecated_octal/index.md | ---
title: 'SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated'
slug: Web/JavaScript/Reference/Errors/Deprecated_octal
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode)-only exception "0-prefixed octal literals and octal escape sequences are
deprecated; for octal literals use the "0o" prefix instead" occurs when deprecated octal
literals and octal escape sequences are used.
## Message
```plain
SyntaxError: Octal literals are not allowed in strict mode. (V8-based)
SyntaxError: "0"-prefixed octal literals are deprecated; use the "0o" prefix instead (Firefox)
SyntaxError: Decimal integer literals with a leading zero are forbidden in strict mode (Safari)
SyntaxError: Octal escape sequences are not allowed in strict mode. (V8-based)
SyntaxError: octal escape sequences can't be used in untagged template literals or in strict mode code (Firefox)
SyntaxError: The only valid numeric escape in strict mode is '\0' (Safari)
```
## Error type
{{jsxref("SyntaxError")}} in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode) only.
## What went wrong?
Octal literals and octal escape sequences are deprecated and will throw a
{{jsxref("SyntaxError")}} in strict mode. The
standardized syntax uses a leading zero followed by a lowercase or uppercase Latin
letter "O" (`0o` or `0O`).
## Examples
### "0"-prefixed octal literals
```js-nolint example-bad
"use strict";
03;
// SyntaxError: "0"-prefixed octal literals are deprecated; use the "0o" prefix instead
```
### Octal escape sequences
```js-nolint example-bad
"use strict";
"\251";
// SyntaxError: octal escape sequences can't be used in untagged template literals or in strict mode code
```
### Valid octal numbers
Use a leading zero followed by the letter "o" or "O":
```js example-good
0o3;
```
For octal escape sequences, you can use hexadecimal escape sequences instead:
```js example-good
"\xA9";
```
## See also
- [Lexical grammar](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#octal)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/missing_parenthesis_after_argument_list/index.md | ---
title: "SyntaxError: missing ) after argument list"
slug: Web/JavaScript/Reference/Errors/Missing_parenthesis_after_argument_list
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "missing ) after argument list" occurs when there is an error
with how a function is called. This might be a typo, a missing operator, or an unescaped
string.
## Message
```plain
SyntaxError: missing ) after argument list (V8-based & Firefox)
SyntaxError: Unexpected identifier 'x'. Expected ')' to end an argument list. (Safari)
```
## Error type
{{jsxref("SyntaxError")}}.
## What went wrong?
There is an error with how a function is called. This might be a typo, a missing
operator, or an unescaped string, for example.
## Examples
Because there is no "+" operator to concatenate the string, JavaScript expects the
argument for the `log` function to be just `"PI: "`. In that case,
it should be terminated by a closing parenthesis.
```js-nolint example-bad
console.log("PI: " Math.PI);
// SyntaxError: missing ) after argument list
```
You can correct the `log` call by adding the `+` operator:
```js example-good
console.log("PI: " + Math.PI);
// "PI: 3.141592653589793"
```
Alternatively, you can consider using a [template literal](/en-US/docs/Web/JavaScript/Reference/Template_literals), or take advantage of the fact that [`console.log`](/en-US/docs/Web/API/console/log_static) accepts multiple parameters:
```js example-good
console.log(`PI: ${Math.PI}`);
console.log("PI:", Math.PI);
```
### Unterminated strings
```js-nolint example-bad
console.log('"Java" + "Script" = \"' + "Java" + 'Script\");
// SyntaxError: missing ) after argument list
```
Here JavaScript thinks that you meant to have `);` inside the string and
ignores it, and it ends up not knowing that you meant the `);` to end the
function `console.log`. To fix this, we could put a`'` after the
"Script" string:
```js example-good
console.log('"Java" + "Script" = "' + "Java" + 'Script"');
// '"Java" + "Script" = "JavaScript"'
```
## See also
- [Functions](/en-US/docs/Web/JavaScript/Guide/Functions) guide
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/missing_name_after_dot_operator/index.md | ---
title: "SyntaxError: missing name after . operator"
slug: Web/JavaScript/Reference/Errors/Missing_name_after_dot_operator
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "missing name after . operator" occurs when there is a problem
with how the dot operator (`.`) is used
for [property access](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors).
## Message
```plain
SyntaxError: missing name after . operator (Firefox)
SyntaxError: Unexpected token '['. Expected a property name after '.'. (Safari)
```
## Error type
{{jsxref("SyntaxError")}}
## What went wrong?
The dot operator (`.`) is used for [property access](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors).
You will have to specify the name of the property that you want to access.
For computed property access, you might need to change your property access from using a
dot to using square brackets. These will allow you to compute an expression. Maybe you
intended to do concatenation instead? A plus operator (`+`) is needed in that
case. Please see the examples below.
## Examples
### Property access
[Property accessors](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors)
in JavaScript use either the dot (.) or square brackets (`[]`), but not both.
Square brackets allow computed property access.
```js-nolint example-bad
const obj = { foo: { bar: "baz", bar2: "baz2" } };
const i = 2;
obj.[foo].[bar]
// SyntaxError: missing name after . operator
obj.foo."bar"+i;
// SyntaxError: missing name after . operator
```
To fix this code, you need to access the object like this:
```js example-good
obj.foo.bar; // "baz"
// or alternatively
obj["foo"]["bar"]; // "baz"
// computed properties require square brackets
obj.foo["bar" + i]; // "baz2"
// or as template literal
obj.foo[`bar${i}`]; // "baz2"
```
### Property access vs. concatenation
If you are coming from another programming language (like [PHP](/en-US/docs/Glossary/PHP)), it is also easy to mix up the dot operator
(`.`) and the concatenation operator (`+`).
```js-nolint example-bad
console.log("Hello" . "world");
// SyntaxError: missing name after . operator
```
Instead you need to use a plus sign for concatenation:
```js example-good
console.log("Hello" + "World");
```
## See also
- [Property accessors](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/non_configurable_array_element/index.md | ---
title: "TypeError: can't delete non-configurable array element"
slug: Web/JavaScript/Reference/Errors/Non_configurable_array_element
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "can't delete non-configurable array element" occurs when it
was attempted to [shorten the length](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length#shortening_an_array)
of an array, but one of the array's elements is [non-configurable](/en-US/docs/Web/JavaScript/Data_structures#properties).
## Message
```plain
TypeError: Cannot delete property '1' of [object Array] (V8-based)
TypeError: can't delete non-configurable array element (Firefox)
TypeError: Unable to delete property. (Safari)
```
## Error type
{{jsxref("TypeError")}}
## What went wrong?
It was attempted to [shorten the length](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length#shortening_an_array)
of an array, but one of the array's elements is [non-configurable](/en-US/docs/Web/JavaScript/Data_structures#properties).
When shortening an array, the elements beyond the new array length will be deleted,
which failed in this situation.
The `configurable` attribute controls whether the property can be deleted
from the object and whether its attributes (other than `writable`) can be
changed.
Usually, properties in an object created by an [array initializer](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#array_literals) are configurable. However, for example, when using {{jsxref("Object.defineProperty()")}}, the property isn't configurable by default.
## Examples
### Non-configurable properties created by Object.defineProperty
The {{jsxref("Object.defineProperty()")}} creates non-configurable properties by
default if you haven't specified them as configurable.
```js example-bad
"use strict";
const arr = [];
Object.defineProperty(arr, 0, { value: 0 });
Object.defineProperty(arr, 1, { value: "1" });
arr.length = 1;
// TypeError: can't delete non-configurable array element
```
You will need to set the elements as configurable, if you intend to shorten the array.
```js example-good
"use strict";
const arr = [];
Object.defineProperty(arr, 0, { value: 0, configurable: true });
Object.defineProperty(arr, 1, { value: "1", configurable: true });
arr.length = 1;
```
### Sealed Arrays
The {{jsxref("Object.seal()")}} function marks all existing elements as
non-configurable.
```js example-bad
"use strict";
const arr = [1, 2, 3];
Object.seal(arr);
arr.length = 1;
// TypeError: can't delete non-configurable array element
```
You either need to remove the {{jsxref("Object.seal()")}} call, or make a copy of it.
In case of a copy, shortening the copy of the array does not modify the original array
length.
```js example-good
"use strict";
const arr = [1, 2, 3];
Object.seal(arr);
// Copy the initial array to shorten the copy
const copy = Array.from(arr);
copy.length = 1;
// arr.length === 3
```
## See also
- [\[\[Configurable\]\]](/en-US/docs/Web/JavaScript/Data_structures#properties)
- {{jsxref("Array/length", "length")}}
- {{jsxref("Object.defineProperty()")}}
- {{jsxref("Object.seal()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/hash_outside_class/index.md | ---
title: "SyntaxError: Unexpected '#' used outside of class body"
slug: Web/JavaScript/Reference/Errors/Hash_outside_class
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "Unexpected '#' used outside of class body" occurs when a hash
("#") is encountered in an unexpected context, most notably
[outside of a class declaration](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties).
Hashes are valid at the beginning of a file as a [hashbang comment](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar),
or inside of a class as part of a private field. You may encounter this error if you forget
the quotation marks when trying to access a DOM identifier as well.
## Message
```plain
SyntaxError: Unexpected '#' used outside of class body.
```
## Error type
{{jsxref("SyntaxError")}}
## What went wrong?
We encountered a `#` somewhere unexpected. This may be due to code moving around and no
longer being part of a class, a hashbang comment found on a line other than the first
line of a file, or accidentally forgetting the quotation marks around a DOM identifier.
## Examples
### Missing quotation marks
For each case, there might be something slightly wrong. For example
```js-nolint example-bad
document.querySelector(#some-element)
```
This can be fixed via
```js example-good
document.querySelector("#some-element");
```
### Outside of a class
```js-nolint example-bad
class ClassWithPrivateField {
#privateField;
constructor() {}
}
this.#privateField = 42;
```
This can be fixed by moving the private field back into the class
```js example-good
class ClassWithPrivateField {
#privateField;
constructor() {
this.#privateField = 42;
}
}
```
## See also
- {{jsxref("SyntaxError")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/bad_regexp_flag/index.md | ---
title: 'SyntaxError: invalid regular expression flag "x"'
slug: Web/JavaScript/Reference/Errors/Bad_regexp_flag
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "invalid regular expression flag" occurs when the flags in a regular expression contain any flag that is not one of: `d`, `g`, `i`, `m`, `s`, `u`, `v`, or `y`.
It may also be raised if the expression contains more than one instance of a valid flag.
## Message
```plain
SyntaxError: Invalid regular expression flags (V8-based)
SyntaxError: invalid regular expression flag x (Firefox)
SyntaxError: Invalid regular expression: invalid flags (Safari)
```
## Error type
{{jsxref("SyntaxError")}}
## What went wrong?
The regular expression contains invalid flags, or valid flags have been used more than once in the expression.
The valid (allowed) flags are `d`, `g`, `i`, `m`, `s`, `u`, `v`, and `y`. They are introduced in more detail in [Regular expressions > Advanced searching with flags](/en-US/docs/Web/JavaScript/Guide/Regular_expressions#advanced_searching_with_flags).
## Examples
In a regular expression literal, which consists of a pattern enclosed between slashes, the flags are defined after the second slash.
Regular expression flags can be used separately or together in any order.
This syntax shows how to declare the flags using the regular expression literal:
```js
const re = /pattern/flags;
```
They can also be defined in the constructor function of the {{jsxref("RegExp")}} object (second parameter):
```js
const re = new RegExp("pattern", "flags");
```
Here is an example showing use of only correct flags.
```js example-good
/foo/g;
/foo/gims;
/foo/uy;
```
Below is an example showing the use of some invalid flags `b`, `a` and `r`:
```js example-bad
/foo/bar;
// SyntaxError: invalid regular expression flag "b"
```
The code below is incorrect, because `W`, `e` and `b` are not valid flags.
```js example-bad
const obj = {
url: /docs/Web,
};
// SyntaxError: invalid regular expression flag "W"
```
An expression containing two slashes is interpreted as a regular expression literal.
Most likely the intent was to create a string literal, using single or double quotes as shown below:
```js example-good
const obj = {
url: "/docs/Web",
};
```
## See also
- [Regular expressions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions) guide
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/missing_semicolon_before_statement/index.md | ---
title: "SyntaxError: missing ; before statement"
slug: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "missing ; before statement" occurs when there is a semicolon (`;`)
missing somewhere and can't be added
by [automatic semicolon insertion (ASI)](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#automatic_semicolon_insertion).
You need to provide a semicolon, so that JavaScript can parse the source code correctly.
## Message
```plain
SyntaxError: Expected ';' (Edge)
SyntaxError: missing ; before statement (Firefox)
```
## Error type
{{jsxref("SyntaxError")}}.
## What went wrong?
There is a semicolon (`;`) missing somewhere. [JavaScript statements](/en-US/docs/Web/JavaScript/Reference/Statements) must
be terminated with semicolons. Some of them are affected
by [automatic semicolon insertion (ASI)](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#automatic_semicolon_insertion),
but in this case you need to provide a semicolon,
so that JavaScript can parse the source code correctly.
However, oftentimes, this error is only a consequence of another error, like not
escaping strings properly, or using `var` wrongly. You might also have too
many parenthesis somewhere. Carefully check the syntax when this error is thrown.
## Examples
### Unescaped strings
This error can occur easily when not escaping strings properly and the JavaScript
engine is expecting the end of your string already. For example:
```js-nolint example-bad
const foo = 'Tom's bar';
// SyntaxError: missing ; before statement
```
You can use double quotes, or escape the apostrophe:
```js-nolint example-good
const foo = "Tom's bar";
// OR
const foo = 'Tom\'s bar';
```
### Declaring properties with keyword
You **cannot** declare properties of an object or array with a
`let`, `const`, or `var` declaration.
```js-nolint example-bad
const obj = {};
const obj.foo = "hi"; // SyntaxError missing ; before statement
const array = [];
const array[0] = "there"; // SyntaxError missing ; before statement
```
Instead, omit the keyword:
```js example-good
const obj = {};
obj.foo = "hi";
const array = [];
array[0] = "there";
```
### Bad keywords
If you come from another programming language, it is also common to use keywords that
don't mean the same or have no meaning at all in JavaScript:
```js-nolint example-bad
def print(info) {
console.log(info);
} // SyntaxError missing ; before statement
```
Instead, use `function` instead of `def`:
```js example-good
function print(info) {
console.log(info);
}
```
## See also
- [Automatic semicolon insertion (ASI)](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#automatic_semicolon_insertion)
- [Statements and declarations](/en-US/docs/Web/JavaScript/Reference/Statements)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/bigint_division_by_zero/index.md | ---
title: "RangeError: BigInt division by zero"
slug: Web/JavaScript/Reference/Errors/BigInt_division_by_zero
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "BigInt division by zero" occurs when a {{jsxref("BigInt")}} is divided by `0n`.
## Message
```plain
RangeError: Division by zero (V8-based)
RangeError: BigInt division by zero (Firefox)
RangeError: 0 is an invalid divisor value. (Safari)
```
## Error type
{{jsxref("RangeError")}}.
## What went wrong?
The divisor of a [division](/en-US/docs/Web/JavaScript/Reference/Operators/Division) or [remainder](/en-US/docs/Web/JavaScript/Reference/Operators/Remainder) operator is `0n`. In {{jsxref("Number")}} arithmetic, this produces [`Infinity`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Infinity), but there's no "infinity value" in BigInts, so an error is issued. Check if the divisor is `0n` before doing the division.
## Examples
### Division by 0n
```js example-bad
const a = 1n;
const b = 0n;
const quotient = a / b;
// RangeError: BigInt division by zero
```
Instead, check if the divisor is `0n` first, and either issue an error with a better message, or fallback to a different value, like `Infinity` or `undefined`.
```js example-good
const a = 1n;
const b = 0n;
const quotient = b === 0n ? undefined : a / b;
```
## See also
- [`BigInt`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
- [Division (`/`)](/en-US/docs/Web/JavaScript/Reference/Operators/Division)
- [Remainder (`%`)](/en-US/docs/Web/JavaScript/Reference/Operators/Remainder)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/is_not_iterable/index.md | ---
title: "TypeError: 'x' is not iterable"
slug: Web/JavaScript/Reference/Errors/is_not_iterable
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "is not iterable" occurs when the value which is given as the
right-hand side of [`for...of`](/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement),
as argument of a function such as {{jsxref("Promise.all")}} or {{jsxref("TypedArray.from")}},
or as the right-hand side of an array [destructuring assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment),
is not an [iterable object](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols).
## Message
```plain
TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator)) (V8-based)
TypeError: x is not iterable (Firefox)
TypeError: undefined is not a function (near '...[x]...') (Safari)
```
## Error type
{{jsxref("TypeError")}}
## What went wrong?
The value which is given as the right-hand side of [`for...of`](/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement),
or as argument of a function such as {{jsxref("Promise.all")}} or {{jsxref("TypedArray.from")}},
or as the right-hand side of an array [destructuring assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment),
is not an [iterable object](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols).
An iterable can be a built-in iterable type such as
{{jsxref("Array")}}, {{jsxref("String")}} or {{jsxref("Map")}}, a generator result, or
an object implementing the [iterable protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol).
## Examples
### Array destructuring a non-iterable
```js example-bad
const myobj = { arrayOrObjProp1: {}, arrayOrObjProp2: [42] };
const {
arrayOrObjProp1: [value1],
arrayOrObjProp2: [value2],
} = myobj; // TypeError: object is not iterable
console.log(value1, value2);
```
The non-iterable might turn to be `undefined` in some runtime environments.
### Iterating over Object properties
In JavaScript, {{jsxref("Object")}}s are not iterable unless they implement
the [iterable protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol).
Therefore, you cannot use [`for...of`](/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement)
to iterate over the properties of an object.
```js example-bad
const obj = { France: "Paris", England: "London" };
for (const p of obj) {
// β¦
} // TypeError: obj is not iterable
```
Instead you have to use {{jsxref("Object.keys")}} or {{jsxref("Object.entries")}}, to
iterate over the properties or entries of an object.
```js example-good
const obj = { France: "Paris", England: "London" };
// Iterate over the property names:
for (const country of Object.keys(obj)) {
const capital = obj[country];
console.log(country, capital);
}
for (const [country, capital] of Object.entries(obj)) {
console.log(country, capital);
}
```
Another option for this use case might be to use a {{jsxref("Map")}}:
```js example-good
const map = new Map();
map.set("France", "Paris");
map.set("England", "London");
// Iterate over the property names:
for (const country of map.keys()) {
const capital = map.get(country);
console.log(country, capital);
}
for (const capital of map.values()) {
console.log(capital);
}
for (const [country, capital] of map.entries()) {
console.log(country, capital);
}
```
### Iterating over a generator
[Generator functions](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators#generator_functions)
are functions you call to produce an iterable object.
```js example-bad
function* generate(a, b) {
yield a;
yield b;
}
for (const x of generate) {
console.log(x);
} // TypeError: generate is not iterable
```
When they are not called, the {{jsxref("Function")}} object corresponding to the
generator is callable, but not iterable. Calling a generator produces an iterable
object which will iterate over the values yielded during the execution of the
generator.
```js example-good
function* generate(a, b) {
yield a;
yield b;
}
for (const x of generate(1, 2)) {
console.log(x);
}
```
### Iterating over a custom iterable
Custom iterables can be created by implementing the
{{jsxref("Symbol.iterator")}} method. You must be certain that your iterator method
returns an object which is an iterator, which is to say it must have a next method.
```js example-bad
const myEmptyIterable = {
[Symbol.iterator]() {
return []; // [] is iterable, but it is not an iterator β it has no next method.
},
};
Array.from(myEmptyIterable); // TypeError: myEmptyIterable is not iterable
```
Here is a correct implementation:
```js example-good
const myEmptyIterable = {
[Symbol.iterator]() {
return [][Symbol.iterator]();
},
};
Array.from(myEmptyIterable); // []
```
## See also
- [Iterable protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol)
- {{jsxref("Object.keys")}}
- {{jsxref("Object.entries")}}
- {{jsxref("Map")}}
- [Generator functions](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators#generator_functions)
- [for...of](/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/reserved_identifier/index.md | ---
title: 'SyntaxError: "x" is a reserved identifier'
slug: Web/JavaScript/Reference/Errors/Reserved_identifier
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "_variable_ is a reserved identifier" occurs
when [reserved keywords](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#keywords) are used as identifiers.
## Message
```plain
SyntaxError: Unexpected reserved word (V8-based)
SyntaxError: implements is a reserved identifier (Firefox)
SyntaxError: Cannot use the reserved word 'implements' as a variable name. (Safari)
```
## Error type
{{jsxref("SyntaxError")}}
## What went wrong?
[Reserved keywords](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#keywords) will throw in
if they are used as identifiers. These are reserved in
strict mode and sloppy mode:
- `enum`
The following are only reserved when they are found in strict mode code:
- `implements`
- `interface`
- {{jsxref("Statements/let", "let")}}
- `package`
- `private`
- `protected`
- `public`
- `static`
## Examples
### Strict and non-strict reserved keywords
The `enum` identifier is generally reserved.
```js-nolint example-bad
const enum = { RED: 0, GREEN: 1, BLUE: 2 };
// SyntaxError: enum is a reserved identifier
```
In strict mode code, more identifiers are reserved.
```js-nolint example-bad
"use strict";
const package = ["potatoes", "rice", "fries"];
// SyntaxError: package is a reserved identifier
```
You'll need to rename these variables.
```js example-good
const colorEnum = { RED: 0, GREEN: 1, BLUE: 2 };
const list = ["potatoes", "rice", "fries"];
```
### Update older browsers
If you are using an older browser that does not yet implement
[`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let) or
[`class`](/en-US/docs/Web/JavaScript/Reference/Statements/class),
for example, you should update to a more recent browser version that does support these
new language features.
```js
"use strict";
class DocArchiver {}
// SyntaxError: class is a reserved identifier
// (throws in older browsers only, e.g. Firefox 44 and older)
```
## See also
- [Lexical grammar](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/not_a_function/index.md | ---
title: 'TypeError: "x" is not a function'
slug: Web/JavaScript/Reference/Errors/Not_a_function
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "is not a function" occurs when there was an attempt to call a
value from a function, but the value is not actually a function.
## Message
```plain
TypeError: "x" is not a function. (V8-based & Firefox & Safari)
```
## Error type
{{jsxref("TypeError")}}
## What went wrong?
It attempted to call a value from a function, but the value is not actually a function.
Some code expects you to provide a function, but that didn't happen.
Maybe there is a typo in the function name? Maybe the object you are calling the method
on does not have this function? For example, JavaScript `Objects` have no
`map` function, but the JavaScript `Array` object does.
There are many built-in functions in need of a (callback) function. You will have to
provide a function in order to have these methods working properly:
- When working with {{jsxref("Array")}} or {{jsxref("TypedArray")}} objects:
- {{jsxref("Array.prototype.every()")}}, {{jsxref("Array.prototype.some()")}},
{{jsxref("Array.prototype.forEach()")}}, {{jsxref("Array.prototype.map()")}},
{{jsxref("Array.prototype.filter()")}}, {{jsxref("Array.prototype.reduce()")}},
{{jsxref("Array.prototype.reduceRight()")}}, {{jsxref("Array.prototype.find()")}}
- When working with {{jsxref("Map")}} and {{jsxref("Set")}} objects:
- {{jsxref("Map.prototype.forEach()")}} and {{jsxref("Set.prototype.forEach()")}}
## Examples
### A typo in the function name
In this case, which happens way too often, there is a typo in the method name:
```js example-bad
const x = document.getElementByID("foo");
// TypeError: document.getElementByID is not a function
```
The correct function name is `getElementById`:
```js example-good
const x = document.getElementById("foo");
```
### Function called on the wrong object
For certain methods, you have to provide a (callback) function and it will work on
specific objects only. In this example, {{jsxref("Array.prototype.map()")}} is used,
which will work with {{jsxref("Array")}} objects only.
```js example-bad
const obj = { a: 13, b: 37, c: 42 };
obj.map(function (num) {
return num * 2;
});
// TypeError: obj.map is not a function
```
Use an array instead:
```js example-good
const numbers = [1, 4, 9];
numbers.map(function (num) {
return num * 2;
}); // [2, 8, 18]
```
### Function shares a name with a pre-existing property
Sometimes when making a class, you may have a property and a function with the same
name. Upon calling the function, the compiler thinks that the function ceases to exist.
```js example-bad
function Dog() {
this.age = 11;
this.color = "black";
this.name = "Ralph";
return this;
}
Dog.prototype.name = function (name) {
this.name = name;
return this;
};
const myNewDog = new Dog();
myNewDog.name("Cassidy"); //Uncaught TypeError: myNewDog.name is not a function
```
Use a different property name instead:
```js example-good
function Dog() {
this.age = 11;
this.color = "black";
this.dogName = "Ralph"; //Using this.dogName instead of .name
return this;
}
Dog.prototype.name = function (name) {
this.dogName = name;
return this;
};
const myNewDog = new Dog();
myNewDog.name("Cassidy"); //Dog { age: 11, color: 'black', dogName: 'Cassidy' }
```
### Using parenthese for multiplication
In math, you can write 2 Γ (3 + 5) as 2\*(3 + 5) or just 2(3 + 5).
Using the latter will throw an error:
```js example-bad
const sixteen = 2(3 + 5);
console.log(`2 x (3 + 5) is ${sixteen}`);
// Uncaught TypeError: 2 is not a function
```
You can correct the code by adding a `*` operator:
```js example-good
const sixteen = 2 * (3 + 5);
console.log(`2 x (3 + 5) is ${sixteen}`);
// 2 x (3 + 5) is 16
```
### Import the exported module correctly
Ensure you are importing the module correctly.
An example helpers library (`helpers.js`)
```js
const helpers = function () {};
helpers.groupBy = function (objectArray, property) {
return objectArray.reduce((acc, obj) => {
const key = obj[property];
acc[key] ??= [];
acc[key].push(obj);
return acc;
}, {});
};
export default helpers;
```
The correct import usage (`App.js`):
```js
import helpers from "./helpers";
```
## See also
- [Functions](/en-US/docs/Web/JavaScript/Reference/Functions)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/reduce_of_empty_array_with_no_initial_value/index.md | ---
title: "TypeError: Reduce of empty array with no initial value"
slug: Web/JavaScript/Reference/Errors/Reduce_of_empty_array_with_no_initial_value
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "reduce of empty array with no initial value" occurs when a
reduce function is used.
## Message
```plain
TypeError: Reduce of empty array with no initial value (V8-based & Firefox & Safari)
```
## Error type
{{jsxref("TypeError")}}
## What went wrong?
In JavaScript, there are several reduce functions:
- {{jsxref("Array.prototype.reduce()")}}, {{jsxref("Array.prototype.reduceRight()")}}
and
- {{jsxref("TypedArray.prototype.reduce()")}},
{{jsxref("TypedArray.prototype.reduceRight()")}}).
These functions optionally take an `initialValue` (which will be used as the
first argument to the first call of the `callback`). However, if no initial
value is provided, it will use the first element of the {{jsxref("Array")}} or
{{jsxref("TypedArray")}} as the initial value. This error is raised when an empty array
is provided because no initial value can be returned in that case.
## Examples
### Invalid cases
This problem appears frequently when combined with a filter
({{jsxref("Array.prototype.filter()")}}, {{jsxref("TypedArray.prototype.filter()")}})
which will remove all elements of the list. Thus leaving none to be used as the initial
value.
```js example-bad
const ints = [0, -1, -2, -3, -4, -5];
ints
.filter((x) => x > 0) // removes all elements
.reduce((x, y) => x + y); // no more elements to use for the initial value.
```
Similarly, the same issue can happen if there is a typo in a selector, or an unexpected
number of elements in a list:
```js example-bad
const names = document.getElementsByClassName("names");
const name_list = Array.prototype.reduce.call(
names,
(acc, name) => acc + ", " + name,
);
```
### Valid cases
These problems can be solved in two different ways.
One way is to actually provide an `initialValue` as the neutral element of
the operator, such as 0 for the addition, 1 for a multiplication, or an empty string for
a concatenation.
```js example-good
const ints = [0, -1, -2, -3, -4, -5];
ints
.filter((x) => x > 0) // removes all elements
.reduce((x, y) => x + y, 0); // the initial value is the neutral element of the addition
```
Another way would be to handle the empty case, either before calling
`reduce`, or in the callback after adding an unexpected dummy initial value.
```js example-good
const names = document.getElementsByClassName("names");
let nameList1 = "";
if (names.length >= 1) {
nameList1 = Array.prototype.reduce.call(
names,
(acc, name) => `${acc}, ${name}`,
);
}
// nameList1 === "" when names is empty.
const nameList2 = Array.prototype.reduce.call(
names,
(acc, name) => {
if (acc === "")
// initial value
return name;
return `${acc}, ${name}`;
},
"",
);
// nameList2 === "" when names is empty.
```
## See also
- {{jsxref("Array.prototype.reduce()")}}
- {{jsxref("Array.prototype.reduceRight()")}}
- {{jsxref("TypedArray.prototype.reduce()")}}
- {{jsxref("TypedArray.prototype.reduceRight()")}}
- {{jsxref("Array")}}
- {{jsxref("TypedArray")}}
- {{jsxref("Array.prototype.filter()")}}
- {{jsxref("TypedArray.prototype.filter()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/bad_break/index.md | ---
title: "SyntaxError: unlabeled break must be inside loop or switch"
slug: Web/JavaScript/Reference/Errors/Bad_break
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "unlabeled break must be inside loop or switch" occurs when a {{jsxref("Statements/break", "break")}} statement is not inside a loop or a {{jsxref("Statements/switch", "switch")}} statement.
## Message
```plain
SyntaxError: Illegal break statement (V8-based)
SyntaxError: unlabeled break must be inside loop or switch (Firefox)
SyntaxError: 'break' is only valid inside a switch or loop statement. (Safari)
```
## Error type
{{jsxref("SyntaxError")}}.
## What went wrong?
{{jsxref("Statements/break", "break")}} statements can be used to exit a loop or a `switch` statement, and using them elsewhere is a syntax error. Alternatively, you can provide a [label](/en-US/docs/Web/JavaScript/Reference/Statements/label) to the `break` statement to break out of any statement with that label β however, if the label does not reference a containing statement, another error [SyntaxError: label not found](/en-US/docs/Web/JavaScript/Reference/Errors/Label_not_found) will be thrown.
## Examples
### Unsyntactic break
`break` cannot be used outside `switch` or loops.
```js-nolint example-bad
let score = 0;
function increment() {
if (score === 100)
break; // SyntaxError: unlabeled break must be inside loop or switch
}
score++;
}
```
Maybe instead of `break`, you intend to use {{jsxref("Statements/return", "return")}} to early-terminate a function.
```js example-good
let score = 0;
function increment() {
if (score === 100) {
return;
}
score++;
}
```
### Using break in callbacks
`break` cannot be used in callbacks, even if the callback is called from a loop.
```js-nolint example-bad
let containingIndex = 0;
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
while (containingIndex < matrix.length) {
matrix[containingIndex].forEach((value) => {
if (value === 5) {
break; // SyntaxError: unlabeled break must be inside loop or switch
}
});
containingIndex++;
}
```
Instead, refactor the code so the `break` is used outside the callback.
```js example-good
let containingIndex = 0;
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
outer: while (containingIndex < matrix.length) {
for (const value of matrix[containingIndex]) {
if (value === 5) {
break outer;
}
}
containingIndex++;
}
```
```js example-good
let containingIndex = 0;
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
while (containingIndex < matrix.length) {
if (matrix[containingIndex].includes(5)) {
break;
}
containingIndex++;
}
```
There's no way to early-terminate a {{jsxref("Array/forEach", "forEach()")}} loop. You can use {{jsxref("Array/some", "some()")}} instead, or convert it to a {{jsxref("Statements/for...of", "for...of")}} loop.
```js-nolint example-bad
array.forEach((value) => {
if (value === 5) {
break; // SyntaxError: unlabeled break must be inside loop or switch
}
// do something with value
});
```
```js example-good
array.some((value) => {
if (value === 5) {
return true;
}
// do something with value
return false;
});
```
```js example-good
for (const value of array) {
if (value === 5) {
break;
}
// do something with value
}
```
## See also
- {{jsxref("Statements/break", "break")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/cant_redefine_property/index.md | ---
title: 'TypeError: can''t redefine non-configurable property "x"'
slug: Web/JavaScript/Reference/Errors/Cant_redefine_property
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "can't redefine non-configurable property" occurs when it was
attempted to redefine a property, but that property is [non-configurable](/en-US/docs/Web/JavaScript/Data_structures#properties).
## Message
```plain
TypeError: Cannot redefine property: "x" (V8-based)
TypeError: can't redefine non-configurable property "x" (Firefox)
TypeError: Attempting to change value of a readonly property. (Safari)
```
## Error type
{{jsxref("TypeError")}}
## What went wrong?
It was attempted to redefine a property, but that property is [non-configurable](/en-US/docs/Web/JavaScript/Data_structures#properties). The
`configurable` attribute controls whether the property can be deleted from
the object and whether its attributes (other than `writable`) can be changed.
Usually, properties in an object created by an
[object initializer](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) are configurable. However, for example, when using
{{jsxref("Object.defineProperty()")}}, the property isn't configurable by default.
## Examples
### Non-configurable properties created by Object.defineProperty
The {{jsxref("Object.defineProperty()")}} creates non-configurable properties if you
haven't specified them as configurable.
```js example-bad
const obj = Object.create({});
Object.defineProperty(obj, "foo", { value: "bar" });
Object.defineProperty(obj, "foo", { value: "baz" });
// TypeError: can't redefine non-configurable property "foo"
```
You will need to set the "foo" property to configurable, if you intend to redefine it
later in the code.
```js example-good
const obj = Object.create({});
Object.defineProperty(obj, "foo", { value: "bar", configurable: true });
Object.defineProperty(obj, "foo", { value: "baz", configurable: true });
```
## See also
- [\[\[Configurable\]\]](/en-US/docs/Web/JavaScript/Data_structures#properties)
- {{jsxref("Object.defineProperty()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/negative_repetition_count/index.md | ---
title: "RangeError: repeat count must be non-negative"
slug: Web/JavaScript/Reference/Errors/Negative_repetition_count
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "repeat count must be non-negative" occurs when the
{{jsxref("String.prototype.repeat()")}} method is used with a `count`
argument that is a negative number.
## Message
```plain
RangeError: Invalid count value: -1 (V8-based)
RangeError: repeat count must be non-negative (Firefox)
RangeError: String.prototype.repeat argument must be greater than or equal to 0 and not be Infinity (Safari)
```
## Error type
{{jsxref("RangeError")}}
## What went wrong?
The {{jsxref("String.prototype.repeat()")}} method has been used. It has a
`count` parameter indicating the number of times to repeat the string. It
must be between 0 and less than positive {{jsxref("Infinity")}} and cannot be a negative
number. The range of allowed values can be described like this: \[0, +β).
## Examples
### Invalid cases
```js example-bad
"abc".repeat(-1); // RangeError
```
### Valid cases
```js example-good
"abc".repeat(0); // ''
"abc".repeat(1); // 'abc'
"abc".repeat(2); // 'abcabc'
"abc".repeat(3.5); // 'abcabcabc' (count will be converted to integer)
```
## See also
- {{jsxref("String.prototype.repeat()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/precision_range/index.md | ---
title: "RangeError: precision is out of range"
slug: Web/JavaScript/Reference/Errors/Precision_range
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "precision is out of range" occurs when a number that's
outside of the range of 0 and 20 (or 21) was passed into `toFixed` or
`toPrecision`.
## Message
```plain
RangeError: toExponential() argument must be between 0 and 100 (V8-based & Safari)
RangeError: toFixed() digits argument must be between 0 and 100 (V8-based & Safari)
RangeError: toPrecision() argument must be between 1 and 100 (V8-based & Safari)
RangeError: precision -1 out of range (Firefox)
```
## Error type
{{jsxref("RangeError")}}
## What went wrong?
There was an out of range precision argument in one of these methods:
- {{jsxref("Number.prototype.toExponential()")}}, which requires the arguments to be between 0 and 100, inclusive.
- {{jsxref("Number.prototype.toFixed()")}}, which requires the arguments to be between 0 and 100, inclusive.
- {{jsxref("Number.prototype.toPrecision()")}}, which requires the arguments to be between 1 and 100, inclusive.
## Examples
### Invalid cases
```js example-bad
(77.1234).toExponential(-1); // RangeError
(77.1234).toExponential(101); // RangeError
(2.34).toFixed(-100); // RangeError
(2.34).toFixed(1001); // RangeError
(1234.5).toPrecision(-1); // RangeError
(1234.5).toPrecision(101); // RangeError
```
### Valid cases
```js example-good
(77.1234).toExponential(4); // 7.7123e+1
(77.1234).toExponential(2); // 7.71e+1
(2.34).toFixed(1); // 2.3
(2.35).toFixed(1); // 2.4 (note that it rounds up in this case)
(5.123456).toPrecision(5); // 5.1235
(5.123456).toPrecision(2); // 5.1
(5.123456).toPrecision(1); // 5
```
## See also
- {{jsxref("Number.prototype.toExponential()")}}
- {{jsxref("Number.prototype.toFixed()")}}
- {{jsxref("Number.prototype.toPrecision()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/bad_await/index.md | ---
title: "SyntaxError: await is only valid in async functions, async generators and modules"
slug: Web/JavaScript/Reference/Errors/Bad_await
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "await is only valid in async functions, async generators and modules" occurs when an {{jsxref("Operators/await", "await")}} expression is used outside of [async functions](/en-US/docs/Web/JavaScript/Reference/Statements/async_function) or [modules](/en-US/docs/Web/JavaScript/Guide/Modules) or other async contexts.
## Message
```plain
SyntaxError: await is only valid in async functions and the top level bodies of modules (V8-based)
SyntaxError: await is only valid in async functions, async generators and modules (Firefox)
SyntaxError: Unexpected identifier (Safari)
```
## Error type
{{jsxref("SyntaxError")}}.
## What went wrong?
JavaScript execution is never blocking: an `await` can never block the execution of the program. Instead, it pauses the execution of the surrounding async task, while allowing other tasks to continue running. Therefore, `await` cannot be used in sync tasks, such as functions, generator functions, or top level of scripts. It is not always apparent whether the current file is a script or a module β see the [Modules guide](/en-US/docs/Web/JavaScript/Guide/Modules#top_level_await) for more information.
## Examples
### Top-level await
You cannot use `await` at the top level of a script:
```html example-bad
<script>
await fetch("https://example.com");
// SyntaxError: await is only valid in async functions, async generators and modules
</script>
```
Instead, make the script a module:
```html example-good
<script type="module">
await fetch("https://example.com");
</script>
```
### Async callbacks
You cannot use `await` in a sync callback:
```js-nolint example-bad
urls.forEach((url) => {
await fetch(url);
// SyntaxError: await is only valid in async functions, async generators and modules
});
```
Instead, make the callback async. See more explanation in the [Using promises guide](/en-US/docs/Web/JavaScript/Guide/Using_promises#composition).
```js example-good
Promise.all(
urls.map(async (url) => {
await fetch(url);
}),
);
```
## See also
- {{jsxref("Operators/await", "await")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/missing_formal_parameter/index.md | ---
title: "SyntaxError: missing formal parameter"
slug: Web/JavaScript/Reference/Errors/Missing_formal_parameter
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "missing formal parameter" occurs when your function
declaration is missing valid parameters.
## Message
```plain
SyntaxError: missing formal parameter (Firefox)
SyntaxError: Unexpected number '3'. Expected a parameter pattern or a ')' in parameter list. (Safari)
SyntaxError: Unexpected string literal "x". Expected a parameter pattern or a ')' in parameter list. (Safari)
```
## Error type
{{jsxref("SyntaxError")}}
## What went wrong?
"Formal parameter" is a fancy way of saying "function parameter". Your function
declaration is missing valid parameters. In the declaration of a function, the
parameters must be [identifiers](/en-US/docs/Glossary/Identifier), not any
value like numbers, strings, or objects. Declaring functions and calling functions are
two separate steps. Declarations require identifier as parameters, and only when calling
(invoking) the function, you provide the values the function should use.
In [JavaScript](/en-US/docs/Glossary/JavaScript), identifiers can contain
only alphanumeric characters (or "$" or "\_"), and may not start with a digit. An
identifier differs from a **string** in that a string is data, while an
identifier is part of the code.
## Examples
### Provide proper function parameters
Function parameters must be identifiers when setting up a function. All these function
declarations fail, as they are providing values for their parameters:
```js-nolint example-bad
function square(3) {
return number * number;
}
// SyntaxError: missing formal parameter
function greet("Howdy") {
return greeting;
}
// SyntaxError: missing formal parameter
function log({ obj: "value"}) {
console.log(arg)
}
// SyntaxError: missing formal parameter
```
You will need to use identifiers in function declarations:
```js example-good
function square(number) {
return number * number;
}
function greet(greeting) {
return greeting;
}
function log(arg) {
console.log(arg);
}
```
You can then call these functions with the arguments you like:
```js
square(2); // 4
greet("Howdy"); // "Howdy"
log({ obj: "value" }); // { obj: "value" }
```
## See also
- [SyntaxError: redeclaration of formal parameter "x"](/en-US/docs/Web/JavaScript/Reference/Errors/Redeclared_parameter)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/cant_be_converted_to_bigint_because_it_isnt_an_integer/index.md | ---
title: "RangeError: x can't be converted to BigInt because it isn't an integer"
slug: Web/JavaScript/Reference/Errors/Cant_be_converted_to_BigInt_because_it_isnt_an_integer
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "x can't be converted to BigInt because it isn't an integer" occurs when the [`BigInt()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/BigInt) function is used on a number that isn't an integer.
## Message
```plain
RangeError: The number 1.5 cannot be converted to a BigInt because it is not an integer (V8-based & Firefox)
RangeError: Not an integer (Safari)
```
## Error type
{{jsxref("RangeError")}}.
## What went wrong?
When using the [`BigInt()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/BigInt) function to convert a number to a BigInt, the number must be an integer (such that [`Number.isInteger`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger) returns true).
## Examples
### Invalid cases
```js example-bad
const a = BigInt(1.5);
// RangeError: The number 1.5 cannot be converted to a BigInt because it is not an integer
const b = BigInt(NaN);
// RangeError: NaN cannot be converted to a BigInt because it is not an integer
```
### Valid cases
```js example-good
const a = BigInt(1);
```
## See also
- [`BigInt()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/BigInt)
- [`Number.isInteger()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/invalid_date/index.md | ---
title: "RangeError: invalid date"
slug: Web/JavaScript/Reference/Errors/Invalid_date
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "invalid date" occurs when a string leading to an invalid date
has been provided to {{jsxref("Date")}} or {{jsxref("Date.parse()")}}.
## Message
```plain
RangeError: Invalid time value (V8-based)
RangeError: invalid date (Firefox)
RangeError: Invalid Date (Safari)
```
## Error type
{{jsxref("RangeError")}}
## What went wrong?
A string leading to an invalid date has been provided to {{jsxref("Date")}} or
{{jsxref("Date.parse()")}}.
## Examples
### Invalid cases
Unrecognizable strings or dates containing illegal element values in ISO formatted
strings usually return {{jsxref("NaN")}}. However, depending on the implementation,
nonβconforming ISO format strings, may also throw `RangeError: invalid date`,
like the following cases in Firefox:
```js example-bad
new Date("foo-bar 2014");
new Date("2014-25-23").toISOString();
new Date("foo-bar 2014").toString();
```
This, however, returns {{jsxref("NaN")}} in Firefox:
```js example-bad
Date.parse("foo-bar 2014"); // NaN
```
For more details, see the {{jsxref("Date.parse()")}} documentation.
### Valid cases
```js example-good
new Date("05 October 2011 14:48 UTC");
new Date(1317826080); // Unix Timestamp for 05 October 2011 14:48:00 UTC
```
## See also
- {{jsxref("Date")}}
- {{jsxref("Date.prototype.parse()")}}
- {{jsxref("Date.prototype.toISOString()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/cant_convert_bigint_to_number/index.md | ---
title: "TypeError: can't convert BigInt to number"
slug: Web/JavaScript/Reference/Errors/Cant_convert_BigInt_to_number
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "can't convert BigInt to number" occurs when an arithmetic operation involves a mix of {{jsxref("BigInt")}} and {{jsxref("Number")}} values.
## Message
```plain
TypeError: Cannot mix BigInt and other types, use explicit conversions (V8-based)
TypeError: BigInts have no unsigned right shift, use >> instead (V8-based)
TypeError: can't convert BigInt to number (Firefox)
TypeError: Invalid mix of BigInt and other type in addition/multiplication/β¦. (Safari)
TypeError: BigInt does not support >>> operator (Safari)
```
## Error type
{{jsxref("TypeError")}}.
## What went wrong?
The two sides of an arithmetic operator must both be BigInts or both not. If an operation involves a mix of BigInts and numbers, it's ambiguous whether the result should be a BigInt or number, since there may be loss of precision in both cases.
The error can also happen if the [unsigned right shift operator (`>>>`)](/en-US/docs/Web/JavaScript/Reference/Operators/Unsigned_right_shift) is used between two BigInts. In Firefox, the message is the same: "can't convert BigInt to number".
## Examples
### Mixing numbers and BigInts in operations
```js example-bad
const sum = 1n + 1;
// TypeError: can't convert BigInt to number
```
Instead, explicitly coerce one side to a BigInt or number.
```js example-good
const sum = 1n + BigInt(1);
const sum2 = Number(1n) + 1;
```
### Using unsigned right shift on BigInts
```js example-bad
const a = 4n >>> 2n;
// TypeError: can't convert BigInt to number
```
Use normal right shift instead.
```js example-good
const a = 4n >> 2n;
```
## See also
- [`BigInt`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/bad_continue/index.md | ---
title: "SyntaxError: continue must be inside loop"
slug: Web/JavaScript/Reference/Errors/Bad_continue
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "continue must be inside loop" occurs when a {{jsxref("Statements/continue", "continue")}} statement is not inside a loop statement.
## Message
```plain
SyntaxError: Illegal continue statement: no surrounding iteration statement (V8-based)
SyntaxError: Illegal continue statement: 'label' does not denote an iteration statement (V8-based)
SyntaxError: continue must be inside loop (Firefox)
SyntaxError: 'continue' is only valid inside a loop statement. (Safari)
SyntaxError: Cannot continue to the label 'label' as it is not targeting a loop. (Safari)
```
## Error type
{{jsxref("SyntaxError")}}.
## What went wrong?
{{jsxref("Statements/continue", "continue")}} statements can be used to continue a loop, and using them elsewhere is a syntax error. Alternatively, you can provide a [label](/en-US/docs/Web/JavaScript/Reference/Statements/label) to the `continue` statement to continue any loop with that label β however, if the label does not reference a containing statement, another error [SyntaxError: label not found](/en-US/docs/Web/JavaScript/Reference/Errors/Label_not_found) will be thrown, and if the label references a statement that is not a loop, a syntax error is still thrown.
## Examples
### Using continue in callbacks
If you want to proceed with the next iteration in a {{jsxref("Array/forEach", "forEach()")}} loop, use {{jsxref("Statements/return", "return")}} instead, or convert it to a {{jsxref("Statements/for...of", "for...of")}} loop.
```js-nolint example-bad
array.forEach((value) => {
if (value === 5) {
continue; // SyntaxError: continue must be inside loop
}
// do something with value
});
```
```js example-good
array.forEach((value) => {
if (value === 5) {
return;
}
// do something with value
});
```
```js example-good
for (const value of array) {
if (value === 5) {
continue;
}
// do something with value
}
```
## See also
- {{jsxref("Statements/continue", "continue")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/illegal_character/index.md | ---
title: "SyntaxError: illegal character"
slug: Web/JavaScript/Reference/Errors/Illegal_character
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "illegal character" occurs when there is an invalid or
unexpected token that doesn't belong at this position in the code.
## Message
```plain
SyntaxError: Invalid character (Edge)
SyntaxError: illegal character (Firefox)
SyntaxError: Invalid or unexpected token (Chrome)
```
## Error type
{{jsxref("SyntaxError")}}
## What went wrong?
There is an invalid or unexpected token that doesn't belong at this position in the
code. Use an editor that supports syntax highlighting and carefully check your code
against mismatches like a minus sign (`-`) versus a dash (`β`)
or simple quotes (`"`) versus non-standard quotation marks (`"`).
## Examples
### Mismatched characters
Some characters look similar, but will cause the parser to fail interpreting your code.
Famous examples of this are quotes, the minus or semicolon
([greek question mark (U+37e)](https://en.wikipedia.org/wiki/Question_mark#Greek_question_mark) looks same).
```js-nolint example-bad
βThis looks like a stringβ; // SyntaxError: illegal character
// β and β are not " but look like it
42 β 13; // SyntaxError: illegal character
// β (en-dash) is not - but looks like it
const foo = "bar"ΝΎ // SyntaxError: illegal character
// <37e> is not ; but looks like it
```
This should work:
```js example-good
"This is actually a string";
42 - 13;
const foo = "bar";
```
Some editors and IDEs will notify you or at least use a slightly different highlighting for it, but not all. When something like this happens to your code and you're not able to find the source of the problem, it's often best to just delete the problematic line and retype it.
### Forgotten characters
It's easy to forget a character here or there.
```js-nolint example-bad
const colors = ["#000", #333", "#666"];
// SyntaxError: illegal character
```
Add the missing quote for `"#333"`.
```js example-good
const colors = ["#000", "#333", "#666"];
```
### Hidden characters
When copy pasting code from external sources, there might be invalid characters. Watch
out!
```js-nolint example-bad
const foo = "bar";β
// SyntaxError: illegal character
```
When inspecting this code in an editor like Vim, you can see that there is actually a
[zero-width space (ZWSP) (U+200B)](https://en.wikipedia.org/wiki/Zero-width_space) character.
```js-nolint
const foo = "bar";<200b>
```
## See also
- [Lexical grammar](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/cant_delete/index.md | ---
title: 'TypeError: property "x" is non-configurable and can''t be deleted'
slug: Web/JavaScript/Reference/Errors/Cant_delete
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "property is non-configurable and can't be deleted" occurs
when it was attempted to delete a property, but that property is [non-configurable](/en-US/docs/Web/JavaScript/Data_structures#properties).
## Message
```plain
TypeError: Cannot delete property 'x' of #<Object> (V8-based)
TypeError: property "x" is non-configurable and can't be deleted (Firefox)
TypeError: Unable to delete property. (Safari)
```
## Error type
{{jsxref("TypeError")}} in strict mode only.
## What went wrong?
It was attempted to delete a property, but that property is [non-configurable](/en-US/docs/Web/JavaScript/Data_structures#properties). The
`configurable` attribute controls whether the property can be deleted from
the object and whether its attributes (other than `writable`) can be changed.
This error happens only in [strict mode code](/en-US/docs/Web/JavaScript/Reference/Strict_mode). In
non-strict code, the operation returns `false`.
## Examples
### Attempting to delete non-configurable properties
Non-configurable properties are not super common, but they can be created using
{{jsxref("Object.defineProperty()")}} or {{jsxref("Object.freeze()")}}.
```js example-bad
"use strict";
const obj = Object.freeze({ name: "Elsa", score: 157 });
delete obj.score; // TypeError
```
```js example-bad
"use strict";
const obj = {};
Object.defineProperty(obj, "foo", { value: 2, configurable: false });
delete obj.foo; // TypeError
```
```js example-bad
"use strict";
const frozenArray = Object.freeze([0, 1, 2]);
frozenArray.pop(); // TypeError
```
There are also a few non-configurable properties built into JavaScript. Maybe you tried
to delete a mathematical constant.
```js example-bad
"use strict";
delete Math.PI; // TypeError
```
## See also
- [`delete`](/en-US/docs/Web/JavaScript/Reference/Operators/delete)
- {{jsxref("Object.defineProperty()")}}
- {{jsxref("Object.freeze()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/array_sort_argument/index.md | ---
title: "TypeError: invalid Array.prototype.sort argument"
slug: Web/JavaScript/Reference/Errors/Array_sort_argument
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "invalid Array.prototype.sort argument" occurs when the argument of {{jsxref("Array.prototype.sort()")}} isn't either {{jsxref("undefined")}} or a function which compares its operands.
## Message
```plain
TypeError: The comparison function must be either a function or undefined (V8-based)
TypeError: invalid Array.prototype.sort argument (Firefox)
TypeError: Array.prototype.sort requires the comparator argument to be a function or undefined (Safari)
```
## Error type
{{jsxref("TypeError")}}
## What went wrong?
The argument of {{jsxref("Array.prototype.sort()")}} is expected to be either {{jsxref("undefined")}} or a function which compares its operands.
## Examples
### Invalid cases
```js example-bad
[1, 3, 2].sort(5); // TypeError
```
### Valid cases
```js example-good
[1, 3, 2].sort(); // [1, 2, 3]
[1, 3, 2].sort((a, b) => a - b); // [1, 2, 3]
```
## See also
- {{jsxref("Array.prototype.sort()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/no_variable_name/index.md | ---
title: "SyntaxError: missing variable name"
slug: Web/JavaScript/Reference/Errors/No_variable_name
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "missing variable name" is a common error.
It is usually caused by omitting a variable name or a typographic error.
## Message
```plain
SyntaxError: missing variable name (Firefox)
SyntaxError: Unexpected token '='. Expected a parameter pattern or a ')' in parameter list. (Safari)
```
## Error type
{{jsxref("SyntaxError")}}
## What went wrong?
A variable is missing a name. The cause is most likely a typo or a forgotten variable name.
Make sure that you've provided the name of the variable before the `=` sign.
When declaring multiple variables at the same time, make sure that the previous lines/declaration does not end with a comma instead of a semicolon.
## Examples
### Missing a variable name
```js-nolint example-bad
const = "foo";
```
It is easy to forget to assign a name for your variable!
```js example-good
const description = "foo";
```
### Reserved keywords can't be variable names
There are a few variable names that are [reserved keywords](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#keywords).
You can't use these. Sorry :(
```js-nolint example-bad
const debugger = "whoop";
// SyntaxError: missing variable name
```
### Declaring multiple variables
Pay special attention to commas when declaring multiple variables.
Is there an excess comma, or did you use commas instead of semicolons?
Did you remember to assign values for all your `const` variables?
```js-nolint example-bad
let x, y = "foo",
const z, = "foo"
const first = document.getElementById("one"),
const second = document.getElementById("two"),
// SyntaxError: missing variable name
```
The fixed version:
```js example-good
let x,
y = "foo";
const z = "foo";
const first = document.getElementById("one");
const second = document.getElementById("two");
```
### Arrays
{{jsxref("Array")}} literals in JavaScript need square brackets around the values.
This won't work:
```js-nolint example-bad
const arr = 1,2,3,4,5;
// SyntaxError: missing variable name
```
This would be correct:
```js example-good
const arr = [1, 2, 3, 4, 5];
```
## See also
- [Lexical grammar](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar)
- {{jsxref("Statements/var", "var")}}
- [Grammar and types](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types) guide
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/redeclared_parameter/index.md | ---
title: 'SyntaxError: redeclaration of formal parameter "x"'
slug: Web/JavaScript/Reference/Errors/Redeclared_parameter
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "redeclaration of formal parameter" occurs when the same
variable name occurs as a function parameter and is then redeclared using a
{{jsxref("Statements/let", "let")}} assignment in a function body again.
## Message
```plain
SyntaxError: Identifier "x" has already been declared (V8-based)
SyntaxError: redeclaration of formal parameter "x" (Firefox)
SyntaxError: Cannot declare a let variable twice: 'x'. (Safari)
```
## Error type
{{jsxref("SyntaxError")}}
## What went wrong?
The same variable name occurs as a function parameter and is then redeclared using a
{{jsxref("Statements/let", "let")}} assignment in a function body again. Redeclaring the
same variable within the same function or block scope using `let` is not
allowed in JavaScript.
## Examples
### Redeclared argument
In this case, the variable "arg" redeclares the argument.
```js-nolint example-bad
function f(arg) {
let arg = "foo";
}
// SyntaxError: redeclaration of formal parameter "arg"
```
If you want to change the value of "arg" in the function body, you can do so, but you
do not need to declare the same variable again. In other words: you can omit the
`let` keyword. If you want to create a new variable, you need to rename it as
conflicts with the function parameter already.
```js example-good
function f(arg) {
arg = "foo";
}
function g(arg) {
let bar = "foo";
}
```
## See also
- {{jsxref("Statements/let", "let")}}
- {{jsxref("Statements/const", "const")}}
- {{jsxref("Statements/var", "var")}}
- [Grammar and types](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types) guide
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/not_a_valid_code_point/index.md | ---
title: "RangeError: argument is not a valid code point"
slug: Web/JavaScript/Reference/Errors/Not_a_valid_code_point
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript exception "Invalid code point" occurs when {{jsxref("NaN")}} values,
negative Integers (-1), non-Integers (5.4), or values larger than 0x10FFFF (1114111) are
used with {{jsxref("String.fromCodePoint()")}}.
## Message
```plain
RangeError: Invalid code point -1 (V8-based)
RangeError: -1 is not a valid code point (Firefox)
RangeError: Arguments contain a value that is out of range of code points (Safari)
```
## Error type
{{jsxref("RangeError")}}
## What went wrong?
{{jsxref("String.fromCodePoint()")}} throws this error when passed {{jsxref("NaN")}}
values, negative Integers (-1), non-Integers (5.4), or values larger than 0x10FFFF
(1114111).
A [code point](https://en.wikipedia.org/wiki/Code_point) is a value in the
Unicode codespace; that is, the range of integers from `0` to
`0x10FFFF`.
## Examples
### Invalid cases
```js example-bad
String.fromCodePoint("_"); // RangeError
String.fromCodePoint(Infinity); // RangeError
String.fromCodePoint(-1); // RangeError
String.fromCodePoint(3.14); // RangeError
String.fromCodePoint(3e-2); // RangeError
String.fromCodePoint(NaN); // RangeError
```
### Valid cases
```js example-good
String.fromCodePoint(42); // "*"
String.fromCodePoint(65, 90); // "AZ"
String.fromCodePoint(0x404); // 'Π' (U+0404)
String.fromCodePoint(0x2f804); // 'π― ' (U+2F804)
String.fromCodePoint(194564); // 'π― '
String.fromCodePoint(0x1d306, 0x61, 0x1d307); // 'πaπ'
```
## See also
- {{jsxref("String.fromCodePoint()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/unterminated_string_literal/index.md | ---
title: "SyntaxError: unterminated string literal"
slug: Web/JavaScript/Reference/Errors/Unterminated_string_literal
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript error "unterminated string literal" occurs when there is an unterminated
[string literal](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#string_literals) somewhere. String literals must be enclosed by single
(`'`) or double (`"`) quotes.
## Message
```plain
SyntaxError: Unterminated string constant (Edge)
SyntaxError: unterminated string literal (Firefox)
```
## Error type
{{jsxref("SyntaxError")}}
## What went wrong?
There is an unterminated
[string literal](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#string_literals) somewhere. String literals must be
enclosed by single (`'`) or double (`"`) quotes. JavaScript makes
no distinction between single-quoted strings and double-quoted strings.
[Escape sequences](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#escape_sequences) work
in strings created with either single or double quotes.
To fix this error, check if:
- you have opening and closing quotes (single or double) for your string literal,
- you have escaped your string literal correctly,
- your string literal isn't split across multiple lines.
## Examples
### Multiple lines
You can't split a string across multiple lines like this in JavaScript:
```js-nolint example-bad
const longString = "This is a very long string which needs
to wrap across multiple lines because
otherwise my code is unreadable.";
// SyntaxError: unterminated string literal
```
Instead, use the [+ operator](/en-US/docs/Web/JavaScript/Reference/Operators/Addition),
a backslash, or [template literals](/en-US/docs/Web/JavaScript/Reference/Template_literals).
The `+` operator variant looks like this:
```js example-good
const longString =
"This is a very long string which needs " +
"to wrap across multiple lines because " +
"otherwise my code is unreadable.";
```
Or you can use the backslash character ("\\") at the end of each line to indicate that
the string will continue on the next line. Make sure there is no space or any other
character after the backslash (except for a line break), or as an indent; otherwise it
will not work. That form looks like this:
```js example-good
const longString =
"This is a very long string which needs \
to wrap across multiple lines because \
otherwise my code is unreadable.";
```
Another possibility is to use [template literals](/en-US/docs/Web/JavaScript/Reference/Template_literals).
```js example-good
const longString = `This is a very long string which needs
to wrap across multiple lines because
otherwise my code is unreadable.`;
```
## See also
- [string literal](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#string_literals)
- [Template literals](/en-US/docs/Web/JavaScript/Reference/Template_literals)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/errors | data/mdn-content/files/en-us/web/javascript/reference/errors/deprecated_caller_or_arguments_usage/index.md | ---
title: "ReferenceError: deprecated caller or arguments usage"
slug: Web/JavaScript/Reference/Errors/Deprecated_caller_or_arguments_usage
page-type: javascript-error
---
{{jsSidebar("Errors")}}
The JavaScript [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode)-only exception
"deprecated caller or arguments usage" occurs when the
deprecated {{jsxref("Function.prototype.caller")}} or {{jsxref("Function.prototype.arguments")}} properties
are used.
## Message
```plain
TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them (V8-based & Firefox)
TypeError: 'arguments', 'callee', and 'caller' cannot be accessed in this context. (Safari)
```
## Error type
{{jsxref("TypeError")}} in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode) only.
## What went wrong?
In [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode), the
{{jsxref("Function.prototype.caller")}} or {{jsxref("Function.prototype.arguments")}} properties are used
and shouldn't be. They are deprecated, because they leak the function caller, are
non-standard, hard to optimize and potentially a performance-harmful feature.
## Examples
### Deprecated function.caller or arguments.callee
{{jsxref("Function.prototype.caller")}} and
[`arguments.callee`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee)
are deprecated (see the reference articles for more information).
```js example-bad
"use strict";
function myFunc() {
if (myFunc.caller === null) {
return "The function was called from the top!";
} else {
return `This function's caller was ${myFunc.caller}`;
}
}
myFunc();
// TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
```
### Function.prototype.arguments
{{jsxref("Function.prototype.arguments")}} is deprecated (see the reference article for more
information).
```js example-bad
"use strict";
function f(n) {
g(n - 1);
}
function g(n) {
console.log(`before: ${g.arguments[0]}`);
if (n > 0) {
f(n);
}
console.log(`after: ${g.arguments[0]}`);
}
f(2);
console.log(`returned: ${g.arguments}`);
// TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
```
## See also
- [Deprecated and obsolete features](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features)
- [Strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode)
- {{jsxref("Function.prototype.arguments")}}
- {{jsxref("Function.prototype.caller")}}
- [`arguments.callee`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference | data/mdn-content/files/en-us/web/javascript/reference/deprecated_and_obsolete_features/index.md | ---
title: Deprecated and obsolete features
slug: Web/JavaScript/Reference/Deprecated_and_obsolete_features
page-type: guide
---
{{jsSidebar("More")}}
This page lists features of JavaScript that are deprecated (that is, still available but planned for removal) and obsolete (that is, no longer usable).
## Deprecated features
These deprecated features can still be used, but should be used with caution because they are not required to be implemented by every JavaScript engine. You should work to remove their use from your code.
Some of these deprecated features are listed in the [Annex B](https://tc39.es/ecma262/multipage/additional-ecmascript-features-for-web-browsers.html) section of the ECMAScript specification. This section is described as normative optional β that is, web browser hosts must implement these features, while non-web hosts may not. These features are likely stable because removing them will cause backward compatibility issues and break legacy websites. (JavaScript has the design goal of "don't break the web".) Still, they are not cross-platform portable and may not be supported by all analysis tools, so you are advised to not use them, as the introduction of Annex B states:
> β¦ All of the language features and behaviors specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification. β¦
>
> β¦ Programmers should not use or assume the existence of these features and behaviors when writing new ECMAScript code. β¦
Some others, albeit in the main spec body, are also marked as normative optional and should not be depended on.
### HTML comments
JavaScript source, if parsed as scripts, allows HTML-like comments, as if the script is part of a `<script>` tag.
The following is valid JavaScript when running in a web browser (or Node.js, which uses the V8 engine powering Chrome):
```js
<!-- comment
console.log("a"); <!-- another comment
console.log("b");
--> More comment
// Logs "a" and "b"
```
`<!--` and `-->` both act like `//`, i.e. starting line comments. `-->` is only valid at the start of a line (to avoid ambiguity with a postfix decrement followed by a greater than operator), while `<!--` can occur anywhere in the line.
### RegExp
The following properties are deprecated. This does not affect their use in [replacement strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace):
- {{jsxref("RegExp/n", "$1β$9")}}
- : Parenthesized substring matches, if any.
- {{jsxref("RegExp/input", "input, $_")}}
- : The string against which a regular expression is matched.
- {{jsxref("RegExp/lastMatch", "lastMatch, $&")}}
- : The last matched substring.
- {{jsxref("RegExp/lastParen", "lastParen, $+")}}
- : The last parenthesized substring match, if any.
- {{jsxref("RegExp/leftContext", "leftContext, $`")}}
- : The substring preceding the most recent match.
- {{jsxref("RegExp/rightContext", "rightContext, $'")}}
- : The substring following the most recent match.
> **Warning:** Avoid using these static properties, as they can cause [issues when interacting with external code](https://github.com/tc39/proposal-regexp-legacy-features/blob/master/subclass-restriction-motivation.md#legacy-static-properties-regexp1-etc)!
The {{jsxref("RegExp/compile", "compile()")}} method is deprecated. Construct a new `RegExp` instance instead.
The following regex syntaxes are deprecated and only available in [Unicode-unaware mode](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode). In Unicode-aware mode, they are all syntax errors:
- [Lookahead assertions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookahead_assertion) can have [quantifiers](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Quantifier).
- [Backreferences](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Backreference) that do not refer to an existing capturing group become [legacy octal escapes](#escape_sequences).
- In [character classes](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class), character ranges where one boundary is a character class makes the `-` become a literal character.
- An escape sequence that's not recognized becomes an ["identity escape"](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape).
- Escape sequences within [character classes](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class) of the form `\cX` where `X` is a number or `_` are decoded in the same way as those with {{Glossary("ASCII")}} letters: `\c0` is the same as `\cP` when taken modulo 32. In addition, if the form `\cX` is encountered anywhere where `X` is not one of the recognized characters, then the backslash is treated as a literal character.
- The sequence `\k` within a regex that doesn't have any [named capturing groups](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_capturing_group) is treated as an identity escape.
- The syntax characters `]`, `{`, and `}` may appear [literally](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Literal_character) without escaping if they cannot be interpreted as the end of a character class or quantifier delimiters.
### Function
- The {{jsxref("Function/caller", "caller")}} property of functions and the [`arguments.callee`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee) property are deprecated and unavailable in strict mode.
- Instead of accessing `arguments` as a property of a function, you should use the {{jsxref("Functions/arguments", "arguments")}} object inside function closures.
### Object
- The [`Object.prototype.__proto__`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto) accessors are deprecated. Use [`Object.getPrototypeOf`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf) and [`Object.setPrototypeOf`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf) instead. This does not apply to the `__proto__` literal key in object literals.
- The [`Object.prototype.__defineGetter__`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__), [`Object.prototype.__defineSetter__`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineSetter__), [`Object.prototype.__lookupGetter__`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupGetter__), and [`Object.prototype.__lookupSetter__`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__lookupSetter__) methods are deprecated. Use [`Object.getOwnPropertyDescriptor`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor) and [`Object.defineProperty`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty) instead.
### String
- HTML wrapper methods like {{jsxref("String.prototype.fontsize")}} and {{jsxref("String.prototype.big")}}.
- {{jsxref("String.prototype.substr")}} probably won't be removed anytime soon, but it's defined in Annex B and hence normative optional.
- `String.prototype.trimLeft` and `String.prototype.trimRight` should be replaced with {{jsxref("String.prototype.trimStart")}} and {{jsxref("String.prototype.trimEnd")}}.
### Date
- The {{jsxref("Date/getYear", "getYear()")}} and {{jsxref("Date/setYear", "setYear()")}} methods are affected by the Year-2000-Problem and have been subsumed by {{jsxref("Date/getFullYear", "getFullYear")}} and {{jsxref("Date/setFullYear", "setFullYear")}}.
- The `toGMTString()` method is deprecated. Use {{jsxref("Date/toUTCString", "toUTCString()")}} instead.
### Escape sequences
- Octal escape sequences (\ followed by one, two, or three octal digits) are deprecated in string and regular expression literals.
- The {{jsxref("escape()")}} and {{jsxref("unescape()")}} functions are deprecated. Use {{jsxref("encodeURI()")}}, {{jsxref("encodeURIComponent()")}}, {{jsxref("decodeURI()")}}, or {{jsxref("decodeURIComponent()")}} to encode and decode escape sequences for special characters.
### Statements
The [`with`](/en-US/docs/Web/JavaScript/Reference/Statements/with) statement is deprecated and unavailable in strict mode.
Initializers in `var` declarations of [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in) loops headers are deprecated and produce [syntax errors](/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_for-in_initializer) in strict mode. They are silently ignored in non-strict mode.
Normally, the `catch` block of a [`try...catch`](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch) statement cannot contain any variable declaration with the same name as the variables bound in the `catch()`. An extension grammar allows the `catch` block to contain a [`var`](/en-US/docs/Web/JavaScript/Reference/Statements/var) declared variable with the same name as the `catch`-bound identifier, but only if the `catch` binding is a simple identifier, not a [destructuring pattern](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment). However, this variable's initialization and assignment would only act on the `catch`-bound identifier, instead of the upper scope variable, and the behavior could be confusing.
```js
var a = 2;
try {
throw 42;
} catch (a) {
var a = 1; // This 1 is assigned to the caught `a`, not the outer `a`.
}
console.log(a); // 2
try {
throw 42;
// Note: identifier changed to `err` to avoid conflict with
// the inner declaration of `a`.
} catch (err) {
var a = 1; // This 1 is assigned to the upper-scope `a`.
}
console.log(a); // 1
```
This is listed in Annex B of the spec and hence may not be implemented everywhere. Avoid any name conflicts between the `catch`-bound identifier and variables declared in the `catch` block.
## Obsolete features
These obsolete features have been entirely removed from JavaScript and can no longer be used as of the indicated version of JavaScript.
### RegExp
The following are now properties of `RegExp` instances, no longer of the `RegExp` constructor:
| Property | Description |
| ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ |
| {{jsxref("RegExp/global", "global")}} | Whether or not to test the regular expression against all possible matches in a string, or only against the first. |
| {{jsxref("RegExp/ignoreCase", "ignoreCase")}} | Whether or not to ignore case while attempting a match in a string. |
| {{jsxref("RegExp/lastIndex", "lastIndex")}} | The index at which to start the next match. |
| {{jsxref("RegExp/multiline", "multiline")}} (also via `RegExp.$*`) | Whether or not to search in strings across multiple lines. |
| {{jsxref("RegExp/source", "source")}} | The text of the pattern. |
The `valueOf()` method is no longer specialized for `RegExp`. It uses {{jsxref("Object.prototype.valueOf()")}}, which returns itself.
### Function
- Functions' `arity` property is obsolete. Use [`length`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length) instead.
### Object
| Property | Description | Alternative |
| ---------------------------- | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `__count__` | Returns the number of enumerable properties directly on a user-defined object. | [`Object.keys()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) |
| `__parent__` | Points to an object's context. | No direct replacement |
| `__iterator__` | Used with [legacy iterators](#legacy_generator_and_iterator). | [`Symbol.iterator`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator) and the new [iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) |
| `__noSuchMethod__` | A method called when a non-existent property is called as method. | {{jsxref("Proxy")}} |
| `Object.prototype.eval()` | Evaluates a string of JavaScript code in the context of the specified object. | No direct replacement |
| `Object.observe()` | Asynchronously observing the changes to an object. | {{jsxref("Proxy")}} |
| `Object.unobserve()` | Remove observers. | {{jsxref("Proxy")}} |
| `Object.getNotifier()` | Create a notifier object that allows to synthetically trigger a change observable with `Object.observe()`. | No direct replacement |
| `Object.prototype.watch()` | Attach a handler callback to a property that gets called when the property is assigned. | {{jsxref("Proxy")}} |
| `Object.prototype.unwatch()` | Remove watch handlers on a property. | {{jsxref("Proxy")}} |
### String
- Non-standard String generic methods like `String.slice(myStr, 0, 12)`, `String.replace(myStr, /\./g, "!")`, etc. have been introduced in Firefox 1.5 (JavaScript 1.6), deprecated in Firefox 53, and removed in Firefox 68. You can use methods on {{jsxref("String", "String.prototype", "instance_methods")}} together with {{jsxref("Function.call")}} instead.
- `String.prototype.quote` is removed from Firefox 37.
- Non-standard `flags` parameter in {{jsxref("String.prototype.search")}}, {{jsxref("String.prototype.match")}}, and {{jsxref("String.prototype.replace")}} are obsolete.
### WeakMap
- `WeakMap.prototype.clear()` was added in Firefox 20 and removed in Firefox 46. It is not possible to traverse all keys in a [`WeakMap`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap).
### Date
- `Date.prototype.toLocaleFormat()`, which used a format string in the same format expected by the `strftime()` function in C, is obsolete. Use [`toLocaleString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString) or [`Intl.DateTimeFormat`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) instead.
### Array
- Non-standard Array generic methods like `Array.slice(myArr, 0, 12)`, `Array.forEach(myArr, myFn)`, etc. have been introduced in Firefox 1.5 (JavaScript 1.6), deprecated in Firefox 68, and removed in Firefox 71. You can use methods on {{jsxref("Array", "Array.prototype", "instance_methods")}} together with {{jsxref("Function.call")}} instead.
| Property | Description | Alternative |
| ------------------- | ------------------------------------------- | ------------------- |
| `Array.observe()` | Asynchronously observing changes to Arrays. | {{jsxref("Proxy")}} |
| `Array.unobserve()` | Remove observers. | {{jsxref("Proxy")}} |
### Number
- `Number.toInteger()` is obsolete. Use [`Math.floor`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor), [`Math.round`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round), or other methods instead.
### Proxy
- `Proxy.create` and `Proxy.createFunction` are obsolete. Use the {{jsxref("Proxy/Proxy", "Proxy()")}} constructor instead.
- The following traps are obsolete:
- `hasOwn` ([bug 980565](https://bugzil.la/980565), Firefox 33).
- `getEnumerablePropertyKeys` ([bug 783829](https://bugzil.la/783829), Firefox 37)
- `getOwnPropertyNames` ([bug 1007334](https://bugzil.la/1007334), Firefox 33)
- `keys` ([bug 1007334](https://bugzil.la/1007334), Firefox 33)
### ParallelArray
- `ParallelArray` is obsolete.
### Statements
- `for each...in` is obsolete. Use {{jsxref("Statements/for...of", "for...of")}} instead.
- let blocks and let expressions are obsolete.
- Expression closures (`function () 1` as a shorthand of `function () { return 1; }`) are obsolete. Use regular {{jsxref("Operators/function", "functions")}} or {{jsxref("Functions/Arrow_functions", "arrow functions", "", 1)}} instead.
### Acquiring source text
The `toSource()` methods of arrays, numbers, strings, etc. and the `uneval()` global function are obsolete. Use [`toString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString), or write your own serialization method instead.
### Legacy generator and iterator
Legacy generator function statements and legacy generator function expressions are removed. The legacy generator function syntax reuses the `function` keyword, which automatically becomes a generator function when there are one or more `yield` expressions in the body β this is now a syntax error. Use [`function*` statements](/en-US/docs/Web/JavaScript/Reference/Statements/function*) and [`function*` expressions](/en-US/docs/Web/JavaScript/Reference/Operators/function*) instead.
Array comprehensions and generator comprehensions are removed.
```js-nolint
// Legacy array comprehensions
[for (x of iterable) x]
[for (x of iterable) if (condition) x]
[for (x of iterable) for (y of iterable) x + y]
// Legacy generator comprehensions
(for (x of iterable) x)
(for (x of iterable) if (condition) x)
(for (x of iterable) for (y of iterable) x + y)
```
Firefox, prior to version 26, implemented another iterator protocol that is similar to the standard [Iterator protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols). An object is an legacy iterator when it implements a `next()` method, which produces a value on each call and throws a `StopIteration` object at the end of iteration. This legacy iterator protocol differs from the standard iterator protocol:
- The value was returned directly as the return value of calls to `next()`, instead of the `value` property of the `IteratorResult` object.
- Iteration termination was expressed by throwing a `StopIteration` object, instead of through the `done` property of the `IteratorResult` object.
This feature, along with the `StopIteration` global constructor, was removed in Firefox 58+. For future-facing usages, consider using [`for...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for...of) loops and the [iterator protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols).
### Sharp variables
Sharp variables are obsolete. To create circular structures, use temporary variables instead.
| 0 |
data/mdn-content/files/en-us/web/javascript/reference | data/mdn-content/files/en-us/web/javascript/reference/statements/index.md | ---
title: Statements and declarations
slug: Web/JavaScript/Reference/Statements
page-type: landing-page
browser-compat: javascript.statements
---
{{jsSidebar("Statements")}}
JavaScript applications consist of statements with an appropriate syntax. A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon. This isn't a keyword, but a group of keywords.
## Statements and declarations by category
For an alphabetical listing see the sidebar on the left.
### Control flow
- {{jsxref("Statements/return", "return")}}
- : Specifies the value to be returned by a function.
- {{jsxref("Statements/break", "break")}}
- : Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.
- {{jsxref("Statements/continue", "continue")}}
- : Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
- {{jsxref("Statements/throw", "throw")}}
- : Throws a user-defined exception.
- {{jsxref("Statements/if...else", "if...else")}}
- : Executes a statement if a specified condition is true. If the condition is false, another statement can be executed.
- {{jsxref("Statements/switch", "switch")}}
- : Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.
- {{jsxref("Statements/try...catch", "try...catch")}}
- : Marks a block of statements to try, and specifies a response, should an exception be thrown.
### Declaring variables
- {{jsxref("Statements/var", "var")}}
- : Declares a variable, optionally initializing it to a value.
- {{jsxref("Statements/let", "let")}}
- : Declares a block scope local variable, optionally initializing it to a value.
- {{jsxref("Statements/const", "const")}}
- : Declares a read-only named constant.
### Functions and classes
- {{jsxref("Statements/function", "function")}}
- : Declares a function with the specified parameters.
- {{jsxref("Statements/function*", "function*")}}
- : Generator Functions enable writing [iterators](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) more easily.
- {{jsxref("Statements/async_function", "async function")}}
- : Declares an async function with the specified parameters.
- {{jsxref("Statements/async_function*", "async function*")}}
- : Asynchronous Generator Functions enable writing async [iterators](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) more easily.
- {{jsxref("Statements/class", "class")}}
- : Declares a class.
### Iterations
- {{jsxref("Statements/do...while", "do...while")}}
- : Creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.
- {{jsxref("Statements/for", "for")}}
- : Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
- {{jsxref("Statements/for...in", "for...in")}}
- : Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
- {{jsxref("Statements/for...of", "for...of")}}
- : Iterates over iterable objects (including {{jsxref("Array", "arrays", "", "true")}}, array-like objects, [iterators and generators](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators)), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
- {{jsxref("Statements/for-await...of", "for await...of")}}
- : Iterates over async iterable objects, array-like objects, [iterators and generators](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
- {{jsxref("Statements/while", "while")}}
- : Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.
### Others
- {{jsxref("Statements/Empty", "Empty", "", 1)}}
- : An empty statement is used to provide no statement, although the JavaScript syntax would expect one.
- {{jsxref("Statements/block", "Block", "", 1)}}
- : A block statement is used to group zero or more statements. The block is delimited by a pair of curly braces.
- {{jsxref("Statements/Expression_statement", "Expression statement", "", 1)}}
- : An expression statement evaluates an expression and discards its result. It allows the expression to perform side effects, such as executing a function or updating a variable.
- {{jsxref("Statements/debugger", "debugger")}}
- : Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect.
- {{jsxref("Statements/export", "export")}}
- : Used to export functions to make them available for imports in external modules, and other scripts.
- {{jsxref("Statements/import", "import")}}
- : Used to import functions exported from an external module, another script.
- {{jsxref("Statements/label", "label", "", 1)}}
- : Provides a statement with an identifier that you can refer to using a `break` or `continue` statement.
- {{jsxref("Statements/with", "with")}} {{deprecated_inline}}
- : Extends the scope chain for a statement.
## Difference between statements and declarations
In this section, we will be mixing two kinds of constructs: [_statements_](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#prod-Statement) and [_declarations_](https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#prod-Declaration). They are two disjoint sets of grammars. The following are declarations:
- {{jsxref("Statements/let", "let")}}
- {{jsxref("Statements/const", "const")}}
- {{jsxref("Statements/function", "function")}}
- {{jsxref("Statements/function*", "function*")}}
- {{jsxref("Statements/async_function", "async function")}}
- {{jsxref("Statements/async_function*", "async function*")}}
- {{jsxref("Statements/class", "class")}}
- {{jsxref("Statements/export", "export")}} (Note: it can only appear at the top-level of a [module](/en-US/docs/Web/JavaScript/Guide/Modules))
- {{jsxref("Statements/import", "import")}} (Note: it can only appear at the top-level of a [module](/en-US/docs/Web/JavaScript/Guide/Modules))
Everything else in the [list above](#statements_and_declarations_by_category) is a statement.
The terms "statement" and "declaration" have a precise meaning in the formal syntax of JavaScript that affects where they may be placed in code. For example, in most control-flow structures, the body only accepts statements β such as the two arms of an [`if...else`](/en-US/docs/Web/JavaScript/Reference/Statements/if...else):
```js-nolint
if (condition)
statement1;
else
statement2;
```
If you use a declaration instead of a statement, it would be a {{jsxref("SyntaxError")}}. For example, a [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let) declaration is not a statement, so you can't use it in its bare form as the body of an `if` statement.
```js-nolint example-bad
if (condition)
let i = 0; // SyntaxError: Lexical declaration cannot appear in a single-statement context
```
On the other hand, [`var`](/en-US/docs/Web/JavaScript/Reference/Statements/var) is a statement, so you can use it on its own as the `if` body.
```js-nolint example-good
if (condition)
var i = 0;
```
You can see declarations as "{{Glossary("binding")}} identifiers to values", and statements as "carrying out actions". The fact that `var` is a statement instead of a declaration is a special case, because it doesn't follow normal lexical scoping rules and may create side effects β in the form of creating global variables, mutating existing `var`-defined variables, and defining variables that are visible outside of its block (because `var`-defined variables aren't block-scoped).
As another example, [labels](/en-US/docs/Web/JavaScript/Reference/Statements/label) can only be attached to statements.
```js-nolint example-bad
label: const a = 1; // SyntaxError: Lexical declaration cannot appear in a single-statement context
```
> **Note:** there's a legacy grammar that allows [function declarations to have labels](/en-US/docs/Web/JavaScript/Reference/Statements/label#labeled_function_declarations), but it's only standardized for compatibility with web reality.
To get around this, you can wrap the declaration in braces β this makes it part of a [block statement](/en-US/docs/Web/JavaScript/Reference/Statements/block).
```js example-good
label: {
const a = 1;
}
if (condition) {
let i = 0;
}
```
## Browser compatibility
{{Compat}}
## See also
- [Expressions and operators](/en-US/docs/Web/JavaScript/Reference/Operators)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/empty/index.md | ---
title: Empty statement
slug: Web/JavaScript/Reference/Statements/Empty
page-type: javascript-statement
browser-compat: javascript.statements.empty
---
{{jsSidebar("Statements")}}
An **empty statement** is used to provide no statement, although the
JavaScript syntax would expect one.
{{EmbedInteractiveExample("pages/js/statement-empty.html")}}
## Syntax
```js-nolint
;
```
## Description
The empty statement is a semicolon (`;`) indicating that no statement will
be executed, even if JavaScript syntax requires one.
The opposite behavior, where you want multiple statements, but JavaScript only allows a
single one, is possible using a [block statement](/en-US/docs/Web/JavaScript/Reference/Statements/block),
which combines several statements into a single one.
## Examples
### Empty loop body
The empty statement is sometimes used with loop statements. See the following example
with an empty loop body:
```js-nolint
const arr = [1, 2, 3];
// Assign all array values to 0
for (let i = 0; i < arr.length; arr[i++] = 0) /* empty statement */ ;
console.log(arr);
// [0, 0, 0]
```
### Unintentional usage
It is a good idea to comment _intentional_ use of the empty statement, as it is
not really obvious to distinguish from a normal semicolon.
In the following example, the usage is probably not intentional:
```js-nolint example-bad
if (condition); // Caution, this "if" does nothing!
killTheUniverse(); // So this always gets executed!!!
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Block statement](/en-US/docs/Web/JavaScript/Reference/Statements/block)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/async_function/index.md | ---
title: async function
slug: Web/JavaScript/Reference/Statements/async_function
page-type: javascript-statement
browser-compat: javascript.statements.async_function
---
{{jsSidebar("Statements")}}
The **`async function`** declaration creates a {{Glossary("binding")}} of a new async function to a given name. The `await` keyword is permitted within the function body, enabling asynchronous, promise-based behavior to be written in a cleaner style and avoiding the need to explicitly configure promise chains.
You can also define async functions using the [`async function` expression](/en-US/docs/Web/JavaScript/Reference/Operators/async_function).
{{EmbedInteractiveExample("pages/js/statement-async.html", "taller")}}
## Syntax
```js-nolint
async function name(param0) {
statements
}
async function name(param0, param1) {
statements
}
async function name(param0, param1, /* β¦, */ paramN) {
statements
}
```
> **Note:** There cannot be a line terminator between `async` and `function`, otherwise a semicolon is [automatically inserted](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#automatic_semicolon_insertion), causing `async` to become an identifier and the rest to become a `function` declaration.
### Parameters
- `name`
- : The function's name.
- `param` {{optional_inline}}
- : The name of a formal parameter for the function. For the parameters' syntax, see the [Functions reference](/en-US/docs/Web/JavaScript/Guide/Functions#function_parameters).
- `statements` {{optional_inline}}
- : The statements comprising the body of the function. The `await`
mechanism may be used.
## Description
An `async function` declaration creates an {{jsxref("AsyncFunction")}} object. Each time when an async function is called, it returns a new {{jsxref("Promise")}} which will be resolved with the value returned by the async function, or rejected with an exception uncaught within the async function.
Async functions can contain zero or more {{jsxref("Operators/await", "await")}} expressions. Await expressions make promise-returning functions behave as though they're synchronous by suspending execution until the returned promise is fulfilled or rejected. The resolved value of the promise is treated as the return value of the await expression. Use of `async` and `await` enables the use of ordinary `try` / `catch` blocks around asynchronous code.
> **Note:** The `await` keyword is only valid inside async functions within regular JavaScript code. If you use it outside of an async function's body, you will get a {{jsxref("SyntaxError")}}.
>
> `await` can be used on its own with [JavaScript modules.](/en-US/docs/Web/JavaScript/Guide/Modules)
> **Note:** The purpose of `async`/`await` is to simplify the syntax
> necessary to consume promise-based APIs. The behavior
> of `async`/`await` is similar to combining [generators](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators) and
> promises.
Async functions always return a promise. If the return value of an async function is
not explicitly a promise, it will be implicitly wrapped in a promise.
For example, consider the following code:
```js
async function foo() {
return 1;
}
```
It is similar to:
```js
function foo() {
return Promise.resolve(1);
}
```
> **Note:**
>
> Even though the return value of an async function behaves as if it's wrapped in a `Promise.resolve`, they are not equivalent.
>
> An async function will return a different _reference_, whereas `Promise.resolve` returns the same reference if the given value is a promise.
>
> It can be a problem when you want to check the equality of a promise and a return value of an async function.
>
> ```js
> const p = new Promise((res, rej) => {
> res(1);
> });
>
> async function asyncReturn() {
> return p;
> }
>
> function basicReturn() {
> return Promise.resolve(p);
> }
>
> console.log(p === basicReturn()); // true
> console.log(p === asyncReturn()); // false
> ```
The body of an async function can be thought of as being split by zero or more await
expressions. Top-level code, up to and including the first await expression (if there is
one), is run synchronously. In this way, an async function without an await expression
will run synchronously. If there is an await expression inside the function body,
however, the async function will always complete asynchronously.
For example:
```js
async function foo() {
await 1;
}
```
It is also equivalent to:
```js
function foo() {
return Promise.resolve(1).then(() => undefined);
}
```
Code after each await expression can be thought of as existing in a `.then`
callback. In this way a promise chain is progressively constructed with each reentrant
step through the function. The return value forms the final link in the chain.
In the following example, we successively await two promises. Progress moves through
function `foo` in three stages.
1. The first line of the body of function `foo` is executed synchronously,
with the await expression configured with the pending promise. Progress through
`foo` is then suspended and control is yielded back to the function that
called `foo`.
2. Some time later, when the first promise has either been fulfilled or rejected,
control moves back into `foo`. The result of the first promise fulfillment
(if it was not rejected) is returned from the await expression. Here `1` is
assigned to `result1`. Progress continues, and the second await expression
is evaluated. Again, progress through `foo` is suspended and control is
yielded.
3. Some time later, when the second promise has either been fulfilled or rejected,
control re-enters `foo`. The result of the second promise resolution is
returned from the second await expression. Here `2` is assigned to
`result2`. Control moves to the return expression (if any). The default
return value of `undefined` is returned as the resolution value of the
current promise.
```js
async function foo() {
const result1 = await new Promise((resolve) =>
setTimeout(() => resolve("1")),
);
const result2 = await new Promise((resolve) =>
setTimeout(() => resolve("2")),
);
}
foo();
```
Note how the promise chain is not built-up in one go. Instead, the promise chain is
constructed in stages as control is successively yielded from and returned to the async
function. As a result, we must be mindful of error handling behavior when dealing with
concurrent asynchronous operations.
For example, in the following code an unhandled promise rejection error will be thrown,
even if a `.catch` handler has been configured further along the promise
chain. This is because `p2` will not be "wired into" the promise chain until
control returns from `p1`.
```js
async function foo() {
const p1 = new Promise((resolve) => setTimeout(() => resolve("1"), 1000));
const p2 = new Promise((_, reject) => setTimeout(() => reject("2"), 500));
const results = [await p1, await p2]; // Do not do this! Use Promise.all or Promise.allSettled instead.
}
foo().catch(() => {}); // Attempt to swallow all errors...
```
`async function` declarations behave similar to {{jsxref("Statements/function", "function")}} declarations β they are [hoisted](/en-US/docs/Glossary/Hoisting) to the top of their scope and can be called anywhere in their scope, and they can be redeclared only in certain contexts.
## Examples
### Async functions and execution order
```js
function resolveAfter2Seconds() {
console.log("starting slow promise");
return new Promise((resolve) => {
setTimeout(() => {
resolve("slow");
console.log("slow promise is done");
}, 2000);
});
}
function resolveAfter1Second() {
console.log("starting fast promise");
return new Promise((resolve) => {
setTimeout(() => {
resolve("fast");
console.log("fast promise is done");
}, 1000);
});
}
async function sequentialStart() {
console.log("== sequentialStart starts ==");
// 1. Start a timer, log after it's done
const slow = resolveAfter2Seconds();
console.log(await slow);
// 2. Start the next timer after waiting for the previous one
const fast = resolveAfter1Second();
console.log(await fast);
console.log("== sequentialStart done ==");
}
async function sequentialWait() {
console.log("== sequentialWait starts ==");
// 1. Start two timers without waiting for each other
const slow = resolveAfter2Seconds();
const fast = resolveAfter1Second();
// 2. Wait for the slow timer to complete, and then log the result
console.log(await slow);
// 3. Wait for the fast timer to complete, and then log the result
console.log(await fast);
console.log("== sequentialWait done ==");
}
async function concurrent1() {
console.log("== concurrent1 starts ==");
// 1. Start two timers concurrently and wait for both to complete
const results = await Promise.all([
resolveAfter2Seconds(),
resolveAfter1Second(),
]);
// 2. Log the results together
console.log(results[0]);
console.log(results[1]);
console.log("== concurrent1 done ==");
}
async function concurrent2() {
console.log("== concurrent2 starts ==");
// 1. Start two timers concurrently, log immediately after each one is done
await Promise.all([
(async () => console.log(await resolveAfter2Seconds()))(),
(async () => console.log(await resolveAfter1Second()))(),
]);
console.log("== concurrent2 done ==");
}
sequentialStart(); // after 2 seconds, logs "slow", then after 1 more second, "fast"
// wait above to finish
setTimeout(sequentialWait, 4000); // after 2 seconds, logs "slow" and then "fast"
// wait again
setTimeout(concurrent1, 7000); // same as sequentialWait
// wait again
setTimeout(concurrent2, 10000); // after 1 second, logs "fast", then after 1 more second, "slow"
```
#### await and concurrency
In `sequentialStart`, execution suspends 2 seconds for the first
`await`, and then another second for the second `await`. The
second timer is not created until the first has already fired, so the code finishes
after 3 seconds.
In `sequentialWait`, both timers are created and then `await`ed.
The timers run concurrently, which means the code finishes in 2 rather than 3 seconds,
i.e. the slowest timer.
However, the `await` calls still run in series, which means the second
`await` will wait for the first one to finish. In this case, the result of
the fastest timer is processed after the slowest.
If you wish to safely perform other jobs after two or more jobs run concurrently and are complete, you must await a call
to {{jsxref("Promise.all()")}} or {{jsxref("Promise.allSettled()")}} before that job.
> **Warning:** The functions `sequentialWait` and `concurrent1`
> are not functionally equivalent.
>
> In `sequentialWait`, if promise `fast` rejects before promise
> `slow` is fulfilled, then an unhandled promise rejection error will be
> raised, regardless of whether the caller has configured a catch clause.
>
> In `concurrent1`, `Promise.all` wires up the promise
> chain in one go, meaning that the operation will fail-fast regardless of the order of
> rejection of the promises, and the error will always occur within the configured
> promise chain, enabling it to be caught in the normal way.
### Rewriting a Promise chain with an async function
An API that returns a {{jsxref("Promise")}} will result in a promise chain, and it
splits the function into many parts. Consider the following code:
```js
function getProcessedData(url) {
return downloadData(url) // returns a promise
.catch((e) => downloadFallbackData(url)) // returns a promise
.then((v) => processDataInWorker(v)); // returns a promise
}
```
it can be rewritten with a single async function as follows:
```js
async function getProcessedData(url) {
let v;
try {
v = await downloadData(url);
} catch (e) {
v = await downloadFallbackData(url);
}
return processDataInWorker(v);
}
```
Alternatively, you can chain the promise with `catch()`:
```js
async function getProcessedData(url) {
const v = await downloadData(url).catch((e) => downloadFallbackData(url));
return processDataInWorker(v);
}
```
In the two rewritten versions, notice there is no `await` statement after the
`return` keyword, although that would be valid too: The return value of an
async function is implicitly wrapped in {{jsxref("Promise.resolve")}} - if
it's not already a promise itself (as in the examples).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Functions](/en-US/docs/Web/JavaScript/Guide/Functions) guide
- [Using promises](/en-US/docs/Web/JavaScript/Guide/Using_promises) guide
- [Functions](/en-US/docs/Web/JavaScript/Reference/Functions)
- {{jsxref("AsyncFunction")}}
- [`async function` expression](/en-US/docs/Web/JavaScript/Reference/Operators/async_function)
- {{jsxref("Statements/function", "function")}}
- {{jsxref("Statements/function*", "function*")}}
- {{jsxref("Statements/async_function*", "async function*")}}
- {{jsxref("Operators/await", "await")}}
- {{jsxref("Promise")}}
- [Decorating async JavaScript functions](https://innolitics.com/10x/javascript-decorators-for-promise-returning-functions/) on innolitics.com (2016)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/export/index.md | ---
title: export
slug: Web/JavaScript/Reference/Statements/export
page-type: javascript-statement
browser-compat: javascript.statements.export
---
{{jsSidebar("Statements")}}
The **`export`** declaration is used to export values from a JavaScript module. Exported values can then be imported into other programs with the {{jsxref("Statements/import", "import")}} declaration or [dynamic import](/en-US/docs/Web/JavaScript/Reference/Operators/import). The value of an imported binding is subject to change in the module that exports it β when a module updates the value of a binding that it exports, the update will be visible in its imported value.
In order to use the `export` declaration in a source file, the file must be interpreted by the runtime as a [module](/en-US/docs/Web/JavaScript/Guide/Modules). In HTML, this is done by adding `type="module"` to the {{HTMLElement("script")}} tag, or by being imported by another module. Modules are automatically interpreted in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode).
## Syntax
```js-nolint
// Exporting declarations
export let name1, name2/*, β¦ */; // also var
export const name1 = 1, name2 = 2/*, β¦ */; // also var, let
export function functionName() { /* β¦ */ }
export class ClassName { /* β¦ */ }
export function* generatorFunctionName() { /* β¦ */ }
export const { name1, name2: bar } = o;
export const [ name1, name2 ] = array;
// Export list
export { name1, /* β¦, */ nameN };
export { variable1 as name1, variable2 as name2, /* β¦, */ nameN };
export { variable1 as "string name" };
export { name1 as default /*, β¦ */ };
// Default exports
export default expression;
export default function functionName() { /* β¦ */ }
export default class ClassName { /* β¦ */ }
export default function* generatorFunctionName() { /* β¦ */ }
export default function () { /* β¦ */ }
export default class { /* β¦ */ }
export default function* () { /* β¦ */ }
// Aggregating modules
export * from "module-name";
export * as name1 from "module-name";
export { name1, /* β¦, */ nameN } from "module-name";
export { import1 as name1, import2 as name2, /* β¦, */ nameN } from "module-name";
export { default, /* β¦, */ } from "module-name";
export { default as name1 } from "module-name";
```
- `nameN`
- : Identifier to be exported (so that it can be imported via {{jsxref("Statements/import", "import")}} in another script). If you use an alias with `as`, the actual exported name can be specified as a string literal, which may not be a valid identifier.
## Description
Every module can have two different types of export, _named export_ and _default export_. You can have multiple named exports per module but only one default export. Each type corresponds to one of the above syntax.
Named exports:
```js
// export features declared elsewhere
export { myFunction2, myVariable2 };
// export individual features (can export var, let,
// const, function, class)
export let myVariable = Math.sqrt(2);
export function myFunction() {
// β¦
}
```
After the `export` keyword, you can use `let`, `const`, and `var` declarations, as well as function or class declarations. You can also use the `export { name1, name2 }` syntax to export a list of names declared elsewhere. Note that `export {}` does not export an empty object β it's a no-op declaration that exports nothing (an empty name list).
Export declarations are not subject to [temporal dead zone](/en-US/docs/Web/JavaScript/Reference/Statements/let#temporal_dead_zone_tdz) rules. You can declare that the module exports `X` before the name `X` itself is declared.
```js
export { x };
const x = 1;
// This works, because `export` is only a declaration, but doesn't
// utilize the value of `x`.
```
Default exports:
```js
// export feature declared elsewhere as default
export { myFunction as default };
// This is equivalent to:
export default myFunction;
// export individual features as default
export default function () { /* β¦ */ }
export default class { /* β¦ */ }
```
> **Note:** Names for export declarations must be distinct from each other. Having exports with duplicate names or using more than one `default` export will result in a {{jsxref("SyntaxError")}} and prevent the module from being evaluated.
The `export default` syntax allows any expression.
```js
export default 1 + 1;
```
As a special case, functions and classes are exported as _declarations_, not expressions, and these declarations can be anonymous. This means functions will be hoisted.
```js
// Works because `foo` is a function declaration,
// not a function expression
foo();
export default function foo() {
console.log("Hi");
}
// It's still technically a declaration, but it's allowed
// to be anonymous
export default function () {
console.log("Hi");
}
```
Named exports are useful when you need to export several values. When importing this module, named exports must be referred to by the exact same name (optionally renaming it with `as`), but the default export can be imported with any name. For example:
```js
// file test.js
const k = 12;
export default k;
```
```js
// some other file
import m from "./test"; // note that we have the freedom to use import m instead of import k, because k was default export
console.log(m); // 12
```
You can also rename named exports to avoid naming conflicts:
```js
export { myFunction as function1, myVariable as variable };
```
You can rename a name to something that's not a valid identifier by using a string literal. For example:
```js
export { myFunction as "my-function" };
```
### Re-exporting / Aggregating
A module can also "relay" values exported from other modules without the hassle of writing two separate import/export statements. This is often useful when creating a single module concentrating various exports from various modules (usually called a "barrel module").
This can be achieved with the "export from" syntax:
```js
export { default as function1, function2 } from "bar.js";
```
Which is comparable to a combination of import and export, except that `function1` and `function2` do not become available inside the current module:
```js
import { default as function1, function2 } from "bar.js";
export { function1, function2 };
```
Most of the "import from" syntaxes have "export from" counterparts.
```js
export { x } from "mod";
export { x as v } from "mod";
export * as ns from "mod";
```
There is also `export * from "mod"`, although there's no `import * from "mod"`. This re-exports all **named** exports from `mod` as the named exports of the current module, but the default export of `mod` is not re-exported. If there are two wildcard exports statements that implicitly re-export the same name, neither one is re-exported.
```js
// -- mod1.js --
export const a = 1;
// -- mod2.js --
export const a = 3;
// -- barrel.js --
export * from "./mod1.js";
export * from "./mod2.js";
// -- main.js --
import * as ns from "./barrel.js";
console.log(ns.a); // undefined
```
Attempting to import the duplicate name directly will throw an error.
```js
import { a } from "./barrel.js";
// SyntaxError: The requested module './barrel.js' contains conflicting star exports for name 'a'
```
The following is syntactically invalid despite its import equivalent:
```js-nolint example-bad
export DefaultExport from "bar.js"; // Invalid
```
The correct way of doing this is to rename the export:
```js
export { default as DefaultExport } from "bar.js";
```
The "export from" syntax allows the `as` token to be omitted, which makes the default export still re-exported as default export.
```js
export { default, function2 } from "bar.js";
```
## Examples
### Using named exports
In a module `my-module.js`, we could include the following code:
```js
// module "my-module.js"
function cube(x) {
return x * x * x;
}
const foo = Math.PI + Math.SQRT2;
const graph = {
options: {
color: "white",
thickness: "2px",
},
draw() {
console.log("From graph draw function");
},
};
export { cube, foo, graph };
```
Then in the top-level module included in your HTML page, we could have:
```js
import { cube, foo, graph } from "./my-module.js";
graph.options = {
color: "blue",
thickness: "3px",
};
graph.draw(); // Logs "From graph draw function"
console.log(cube(3)); // 27
console.log(foo); // 4.555806215962888
```
It is important to note the following:
- You need to include this script in your HTML with a {{HTMLElement("script")}} element of `type="module"`, so that it gets recognized as a module and dealt with appropriately.
- You can't run JS modules via a `file://` URL β you'll get [CORS](/en-US/docs/Web/HTTP/CORS) errors. You need to run it via an HTTP server.
### Using the default export
If we want to export a single value or to have a fallback value for your module, you could use a default export:
```js
// module "my-module.js"
export default function cube(x) {
return x * x * x;
}
```
Then, in another script, it is straightforward to import the default export:
```js
import cube from "./my-module.js";
console.log(cube(3)); // 27
```
### Using export from
Let's take an example where we have the following hierarchy:
- `childModule1.js`: exporting `myFunction` and `myVariable`
- `childModule2.js`: exporting `MyClass`
- `parentModule.js`: acting as an aggregator (and doing nothing else)
- top level module: consuming the exports of `parentModule.js`
This is what it would look like using code snippets:
```js
// In childModule1.js
function myFunction() {
console.log("Hello!");
}
const myVariable = 1;
export { myFunction, myVariable };
```
```js
// In childModule2.js
class MyClass {
constructor(x) {
this.x = x;
}
}
export { MyClass };
```
```js
// In parentModule.js
// Only aggregating the exports from childModule1 and childModule2
// to re-export them
export { myFunction, myVariable } from "childModule1.js";
export { MyClass } from "childModule2.js";
```
```js
// In top-level module
// We can consume the exports from a single module since parentModule
// "collected"/"bundled" them in a single source
import { myFunction, myVariable, MyClass } from "parentModule.js";
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Statements/import", "import")}}
- [JavaScript modules](/en-US/docs/Web/JavaScript/Guide/Modules) guide
- [ES6 in Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/) on hacks.mozilla.org (2015)
- [ES modules: A cartoon deep-dive](https://hacks.mozilla.org/2018/03/es-modules-a-cartoon-deep-dive/) on hacks.mozilla.org (2018)
- [Exploring JS, Ch.16: Modules](https://exploringjs.com/es6/ch_modules.html) by Dr. Axel Rauschmayer
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/function/index.md | ---
title: function
slug: Web/JavaScript/Reference/Statements/function
page-type: javascript-statement
browser-compat: javascript.statements.function
---
{{jsSidebar("Statements")}}
The **`function`** declaration creates a {{Glossary("binding")}} of a new function to a given name.
You can also define functions using the [`function` expression](/en-US/docs/Web/JavaScript/Reference/Operators/function).
{{EmbedInteractiveExample("pages/js/statement-function.html", "shorter")}}
## Syntax
```js-nolint
function name(param0) {
statements
}
function name(param0, param1) {
statements
}
function name(param0, param1, /* β¦, */ paramN) {
statements
}
```
### Parameters
- `name`
- : The function name.
- `param` {{optional_inline}}
- : The name of a formal parameter for the function. Maximum number of arguments varies in different engines. For the parameters' syntax, see the [Functions reference](/en-US/docs/Web/JavaScript/Guide/Functions#function_parameters).
- `statements` {{optional_inline}}
- : The statements which comprise the body of the function.
## Description
A `function` declaration creates a {{jsxref("Function")}} object. Each time when a function is called, it returns the value specified by the last executed {{jsxref("Statements/return", "return")}} statement, or `undefined` if the end of the function body is reached. See [functions](/en-US/docs/Web/JavaScript/Reference/Functions) for detailed information on functions.
`function` declarations behave like a mix of {{jsxref("Statements/var", "var")}} and {{jsxref("Statements/let", "let")}}:
- Like `let`, in strict mode, [function declarations are scoped to the most closely containing block](#block-level_function_declaration).
- Like `let`, function declarations at the top level of a module or within blocks in strict mode cannot be [redeclared](#redeclarations) by any other declaration.
- Like `var`, function declarations at the top level of a script (strict or non-strict) become properties on {{jsxref("globalThis")}}. Function declarations at the top level of a script or function body (strict or non-strict) can be redeclared by another `function` or `var`.
- Like both, function declarations can be re-assigned, but you should avoid doing so.
- Unlike either, function declarations are [hoisted](#hoisting) together with its value and can be called anywhere in its scope.
### Block-level function declaration
> **Warning:** In [non-strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode), function declarations inside blocks behave strangely. Only declare functions in blocks if you are in strict mode.
Functions can be conditionally declared β that is, a function statement can be nested within an [`if`](/en-US/docs/Web/JavaScript/Reference/Statements/if...else) statement. However, in non-strict mode, the results are inconsistent across implementations.
```js
console.log(
`'foo' name ${
"foo" in globalThis ? "is" : "is not"
} global. typeof foo is ${typeof foo}`,
);
if (false) {
function foo() {
return 1;
}
}
// In Chrome:
// 'foo' name is global. typeof foo is undefined
//
// In Firefox:
// 'foo' name is global. typeof foo is undefined
//
// In Safari:
// 'foo' name is global. typeof foo is function
```
The scoping and hoisting effect won't change regardless of whether the `if` body is actually executed.
```js
console.log(
`'foo' name ${
"foo" in globalThis ? "is" : "is not"
} global. typeof foo is ${typeof foo}`,
);
if (true) {
function foo() {
return 1;
}
}
// In Chrome:
// 'foo' name is global. typeof foo is undefined
//
// In Firefox:
// 'foo' name is global. typeof foo is undefined
//
// In Safari:
// 'foo' name is global. typeof foo is function
```
In [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode), [block](/en-US/docs/Web/JavaScript/Reference/Statements/block)-level function declarations are scoped to that block and are hoisted to the top of the block.
```js
"use strict";
{
foo(); // Logs "foo"
function foo() {
console.log("foo");
}
}
console.log(
`'foo' name ${
"foo" in globalThis ? "is" : "is not"
} global. typeof foo is ${typeof foo}`,
);
// 'foo' name is not global. typeof foo is undefined
```
### Hoisting
Function declarations in JavaScript are [hoisted](/en-US/docs/Glossary/Hoisting) to the top of the enclosing function or global scope. You can use the function before you declared it:
```js
hoisted(); // Logs "foo"
function hoisted() {
console.log("foo");
}
```
Note that [function expressions](/en-US/docs/Web/JavaScript/Reference/Operators/function) are not hoisted:
```js
notHoisted(); // TypeError: notHoisted is not a function
var notHoisted = function () {
console.log("bar");
};
```
### Redeclarations
Whether `function` declarations can be redeclared in the same scope depends on what scope it's contained in.
At the top level of a script, `function` declarations behave like `var` and can be redeclared by another `function` or `var` but not by {{jsxref("Statements/let", "let")}}, {{jsxref("Statements/const", "const")}}, or {{jsxref("Statements/class", "class")}}.
```js-nolint example-bad
function a(b) {}
function a(b, c) {}
console.log(a.length); // 2
let a = 2; // SyntaxError: Identifier 'a' has already been declared
```
When `function` declarations are redeclared by `var`, the `var` declaration's initializer always overrides the function's value, regardless of their relative position. This is because function declarations are hoisted before any initializer gets evaluated, so the initializer comes later and overrides the value.
```js
var a = 1;
function a() {}
console.log(a); // 1
```
At the top level of a function's body, `function` also behaves like `var` and can be redeclared or have the same name as a parameter.
```js
function foo(a) {
function a() {}
console.log(typeof a);
}
foo(2); // Logs "function"
```
At the top level of a module or a block in strict mode, `function` declarations behave like `let` and cannot be redeclared by any other declaration.
```js-nolint example-bad
// Assuming current source is a module
function foo() {}
function foo() {} // SyntaxError: Identifier 'foo' has already been declared
```
```js-nolint example-bad
"use strict";
{
function foo() {}
function foo() {} // SyntaxError: Identifier 'foo' has already been declared
}
```
A `function` declaration within a `catch` block cannot have the same name as the `catch`-bound identifier, even in non-strict mode.
```js-nolint example-bad
try {
} catch (e) {
function e() {} // SyntaxError: Identifier 'e' has already been declared
}
```
## Examples
### Using function
The following code declares a function that returns the total amount of sales, when given the number of units sold of three products.
```js
function calcSales(unitsA, unitsB, unitsC) {
return unitsA * 79 + unitsB * 129 + unitsC * 699;
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Functions](/en-US/docs/Web/JavaScript/Guide/Functions) guide
- [Functions](/en-US/docs/Web/JavaScript/Reference/Functions)
- {{jsxref("Function")}}
- [`function` expression](/en-US/docs/Web/JavaScript/Reference/Operators/function)
- {{jsxref("Statements/function*", "function*")}}
- {{jsxref("Statements/async_function", "async function")}}
- {{jsxref("Statements/async_function*", "async function*")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/try...catch/index.md | ---
title: try...catch
slug: Web/JavaScript/Reference/Statements/try...catch
page-type: javascript-statement
browser-compat: javascript.statements.try_catch
---
{{jsSidebar("Statements")}}
The **`try...catch`** statement is comprised of a `try` block and either a `catch` block, a `finally` block, or both. The code in the `try` block is executed first, and if it throws an exception, the code in the `catch` block will be executed. The code in the `finally` block will always be executed before control flow exits the entire construct.
{{EmbedInteractiveExample("pages/js/statement-trycatch.html")}}
## Syntax
```js-nolint
try {
tryStatements
} catch (exceptionVar) {
catchStatements
} finally {
finallyStatements
}
```
- `tryStatements`
- : The statements to be executed.
- `catchStatements`
- : Statement that is executed if an exception is thrown in the `try` block.
- `exceptionVar` {{optional_inline}}
- : An optional [identifier or pattern](#catch_binding) to hold the caught exception for the associated `catch` block. If the `catch` block does not use the exception's value, you can omit the `exceptionVar` and its surrounding parentheses.
- `finallyStatements`
- : Statements that are executed before control flow exits the `try...catch...finally` construct. These statements execute regardless of whether an exception was thrown or caught.
## Description
The `try` statement always starts with a `try` block. Then, a `catch` block or a `finally` block must be present. It's also possible to have both `catch` and `finally` blocks. This gives us three forms for the `try` statement:
- `try...catch`
- `try...finally`
- `try...catch...finally`
Unlike other constructs such as [`if`](/en-US/docs/Web/JavaScript/Reference/Statements/if...else) or [`for`](/en-US/docs/Web/JavaScript/Reference/Statements/for), the `try`, `catch`, and `finally` blocks must be _blocks_, instead of single statements.
```js-nolint example-bad
try doSomething(); // SyntaxError
catch (e) console.log(e);
```
A `catch` block contains statements that specify what to do if an exception is thrown in the `try` block. If any statement within the `try` block (or in a function called from within the `try` block) throws an exception, control is immediately shifted to the `catch` block. If no exception is thrown in the `try` block, the `catch` block is skipped.
The `finally` block will always execute before control flow exits the `try...catch...finally` construct. It always executes, regardless of whether an exception was thrown or caught.
You can nest one or more `try` statements. If an inner `try` statement does not have a `catch` block, the enclosing `try` statement's `catch` block is used instead.
You can also use the `try` statement to handle JavaScript exceptions. See the [JavaScript Guide](/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#exception_handling_statements) for more information on JavaScript exceptions.
### Catch binding
When an exception is thrown in the `try` block, `exceptionVar` (i.e., the `e` in `catch (e)`) holds the exception value. You can use this {{Glossary("binding")}} to get information about the exception that was thrown. This {{Glossary("binding")}} is only available in the `catch` block's {{Glossary("Scope", "scope")}}.
It doesn't need to be a single identifier. You can use a [destructuring pattern](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) to assign multiple identifiers at once.
```js
try {
throw new TypeError("oops");
} catch ({ name, message }) {
console.log(name); // "TypeError"
console.log(message); // "oops"
}
```
The bindings created by the `catch` clause live in the same scope as the `catch` block, so any variables declared in the `catch` block cannot have the same name as the bindings created by the `catch` clause. (There's [one exception to this rule](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#statements), but it's a deprecated syntax.)
```js-nolint example-bad
try {
throw new TypeError("oops");
} catch ({ name, message }) {
var name; // SyntaxError: Identifier 'name' has already been declared
let message; // SyntaxError: Identifier 'message' has already been declared
}
```
The exception binding is writable. For example, you may want to normalize the exception value to make sure it's an {{jsxref("Error")}} object.
```js
try {
throw "Oops; this is not an Error object";
} catch (e) {
if (!(e instanceof Error)) {
e = new Error(e);
}
console.error(e.message);
}
```
If you don't need the exception value, you can omit it along with the enclosing parentheses.
```js
function isValidJSON(text) {
try {
JSON.parse(text);
return true;
} catch {
return false;
}
}
```
### The finally block
The `finally` block contains statements to execute after the `try` block and `catch` block(s) execute, but before the statements following the `try...catch...finally` block. Control flow will always enter the `finally` block, which can proceed in one of the following ways:
- Immediately after the `try` block finishes execution normally (and no exceptions were thrown);
- Immediately after the `catch` block finishes execution normally;
- Immediately before a control-flow statement (`return`, `throw`, `break`, `continue`) is executed in the `try` block or `catch` block.
If an exception is thrown from the `try` block, even when there's no `catch` block to handle the exception, the `finally` block still executes, in which case the exception is still thrown immediately after the `finally` block finishes executing.
The following example shows one use case for the `finally` block. The code opens a file and then executes statements that use the file; the `finally` block makes sure the file always closes after it is used even if an exception was thrown.
```js
openMyFile();
try {
// tie up a resource
writeMyFile(theData);
} finally {
closeMyFile(); // always close the resource
}
```
Control flow statements (`return`, `throw`, `break`, `continue`) in the `finally` block will "mask" any completion value of the `try` block or `catch` block. In this example, the `try` block tries to return 1, but before returning, the control flow is yielded to the `finally` block first, so the `finally` block's return value is returned instead.
```js
function doIt() {
try {
return 1;
} finally {
return 2;
}
}
doIt(); // returns 2
```
It is generally a bad idea to have control flow statements in the `finally` block. Only use it for cleanup code.
## Examples
### Unconditional catch block
When a `catch` block is used, the `catch` block is executed when any exception is thrown from within the `try` block. For example, when the exception occurs in the following code, control transfers to the `catch` block.
```js
try {
throw "myException"; // generates an exception
} catch (e) {
// statements to handle any exceptions
logMyErrors(e); // pass exception object to error handler
}
```
The `catch` block specifies an identifier (`e` in the example above) that holds the value of the exception; this value is only available in the {{Glossary("Scope", "scope")}} of the `catch` block.
### Conditional catch blocks
You can create "Conditional `catch` blocks" by combining `try...catch` blocks with `if...else if...else` structures, like this:
```js
try {
myroutine(); // may throw three types of exceptions
} catch (e) {
if (e instanceof TypeError) {
// statements to handle TypeError exceptions
} else if (e instanceof RangeError) {
// statements to handle RangeError exceptions
} else if (e instanceof EvalError) {
// statements to handle EvalError exceptions
} else {
// statements to handle any unspecified exceptions
logMyErrors(e); // pass exception object to error handler
}
}
```
A common use case for this is to only catch (and silence) a small subset of expected errors, and then re-throw the error in other cases:
```js
try {
myRoutine();
} catch (e) {
if (e instanceof RangeError) {
// statements to handle this very common expected error
} else {
throw e; // re-throw the error unchanged
}
}
```
This may mimic the syntax from other languages, like Java:
```java
try {
myRoutine();
} catch (RangeError e) {
// statements to handle this very common expected error
}
// Other errors are implicitly re-thrown
```
### Nested try blocks
First, let's see what happens with this:
```js
try {
try {
throw new Error("oops");
} finally {
console.log("finally");
}
} catch (ex) {
console.error("outer", ex.message);
}
// Logs:
// "finally"
// "outer" "oops"
```
Now, if we already caught the exception in the inner `try` block by adding a `catch` block:
```js
try {
try {
throw new Error("oops");
} catch (ex) {
console.error("inner", ex.message);
} finally {
console.log("finally");
}
} catch (ex) {
console.error("outer", ex.message);
}
// Logs:
// "inner" "oops"
// "finally"
```
And now, let's rethrow the error.
```js
try {
try {
throw new Error("oops");
} catch (ex) {
console.error("inner", ex.message);
throw ex;
} finally {
console.log("finally");
}
} catch (ex) {
console.error("outer", ex.message);
}
// Logs:
// "inner" "oops"
// "finally"
// "outer" "oops"
```
Any given exception will be caught only once by the nearest enclosing `catch` block unless it is rethrown. Of course, any new exceptions raised in the "inner" block (because the code in `catch` block may do something that throws), will be caught by the "outer" block.
### Returning from a finally block
If the `finally` block returns a value, this value becomes the return value of the entire `try-catch-finally` statement, regardless of any `return` statements in the `try` and `catch` blocks. This includes exceptions thrown inside of the `catch` block:
```js
(() => {
try {
try {
throw new Error("oops");
} catch (ex) {
console.error("inner", ex.message);
throw ex;
} finally {
console.log("finally");
return;
}
} catch (ex) {
console.error("outer", ex.message);
}
})();
// Logs:
// "inner" "oops"
// "finally"
```
The outer "oops" is not thrown because of the return in the `finally` block. The same would apply to any value returned from the `catch` block.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Error")}}
- {{jsxref("Statements/throw", "throw")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/return/index.md | ---
title: return
slug: Web/JavaScript/Reference/Statements/return
page-type: javascript-statement
browser-compat: javascript.statements.return
---
{{jsSidebar("Statements")}}
The **`return`** statement ends function execution and specifies a value to be returned to the function caller.
{{EmbedInteractiveExample("pages/js/statement-return.html")}}
## Syntax
```js-nolint
return;
return expression;
```
- `expression` {{optional_inline}}
- : The expression whose value is to be returned. If omitted, `undefined` is returned.
## Description
The `return` statement can only be used within function bodies. When a `return` statement is used in a function body, the execution of the function is stopped. The `return` statement has different effects when placed in different functions:
- In a plain function, the call to that function evaluates to the return value.
- In an async function, the produced promise is resolved with the returned value.
- In a generator function, the produced generator object's `next()` method returns `{ done: true, value: returnedValue }`.
- In an async generator function, the produced async generator object's `next()` method returns a promise fulfilled with `{ done: true, value: returnedValue }`.
If a `return` statement is executed within a {{jsxref("Statements/try...catch", "try")}} block, its `finally` block, if present, is first executed, before the value is actually returned.
### Automatic semicolon insertion
The syntax forbids line terminators between the `return` keyword and the expression to be returned.
```js-nolint example-bad
return
a + b;
```
The code above is transformed by [automatic semicolon insertion (ASI)](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#automatic_semicolon_insertion) into:
```js-nolint
return;
a + b;
```
This makes the function return `undefined` and the `a + b` expression is never evaluated. This may generate [a warning in the console](/en-US/docs/Web/JavaScript/Reference/Errors/Stmt_after_return).
To avoid this problem (to prevent ASI), you could use parentheses:
```js-nolint
return (
a + b
);
```
## Examples
### Interrupt a function
A function immediately stops at the point where `return` is called.
```js
function counter() {
// Infinite loop
for (let count = 1; ; count++) {
console.log(`${count}A`); // Until 5
if (count === 5) {
return;
}
console.log(`${count}B`); // Until 4
}
console.log(`${count}C`); // Never appears
}
counter();
// Logs:
// 1A
// 1B
// 2A
// 2B
// 3A
// 3B
// 4A
// 4B
// 5A
```
### Returning a function
See also the article about [Closures](/en-US/docs/Web/JavaScript/Closures).
```js
function magic() {
return function calc(x) {
return x * 42;
};
}
const answer = magic();
answer(1337); // 56154
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Functions](/en-US/docs/Web/JavaScript/Reference/Functions)
- [Closures](/en-US/docs/Web/JavaScript/Closures)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/for...in/index.md | ---
title: for...in
slug: Web/JavaScript/Reference/Statements/for...in
page-type: javascript-statement
browser-compat: javascript.statements.for_in
---
{{jsSidebar("Statements")}}
The **`for...in`** statement iterates over all [enumerable string properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) of an object (ignoring properties keyed by [symbols](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol)), including inherited enumerable properties.
{{EmbedInteractiveExample("pages/js/statement-forin.html")}}
## Syntax
```js-nolint
for (variable in object)
statement
```
### Parameters
- `variable`
- : Receives a string property name on each iteration. May be either a declaration with [`const`](/en-US/docs/Web/JavaScript/Reference/Statements/const), [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let), or [`var`](/en-US/docs/Web/JavaScript/Reference/Statements/var), or an [assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Assignment) target (e.g. a previously declared variable, an object property, or a [destructuring assignment pattern](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)). Variables declared with `var` are not local to the loop, i.e. they are in the same scope the `for...in` loop is in.
- `object`
- : Object whose non-symbol enumerable properties are iterated over.
- `statement`
- : A statement to be executed on every iteration. May reference `variable`. You can use a [block statement](/en-US/docs/Web/JavaScript/Reference/Statements/block) to execute multiple statements.
## Description
The loop will iterate over all enumerable properties of the object itself and those the object inherits from its prototype chain (properties of nearer prototypes take precedence over those of prototypes further away from the object in its prototype chain).
A `for...in` loop only iterates over enumerable, non-symbol properties. Objects created from builtβin constructors like `Array` and `Object` have inherited nonβenumerable properties from `Array.prototype` and `Object.prototype`, such as {{jsxref("Array")}}'s {{jsxref("Array/indexOf", "indexOf()")}} method or {{jsxref("Object")}}'s {{jsxref("Object/toString", "toString()")}} method, which will not be visited in the `for...in` loop.
The traversal order, as of modern ECMAScript specification, is well-defined and consistent across implementations. Within each component of the prototype chain, all non-negative integer keys (those that can be array indices) will be traversed first in ascending order by value, then other string keys in ascending chronological order of property creation.
The `variable` part of `for...in` accepts anything that can come before the `=` operator. You can use {{jsxref("Statements/const", "const")}} to declare the variable as long as it's not reassigned within the loop body (it can change between iterations, because those are two separate variables). Otherwise, you can use {{jsxref("Statements/let", "let")}}. You can use [destructuring](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) to assign multiple local variables, or use a property accessor like `for (x.y in iterable)` to assign the value to an object property.
A [legacy syntax](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#statements) allows `var` declarations of the loop variable to have an initializer. This throws a [syntax error](/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_for-in_initializer) in strict mode and is ignored in nonβstrict mode.
### Deleted, added, or modified properties
`for...in` visits property keys in the following fashion:
1. It first gets all own string keys of the current object, in a fashion very similar to {{jsxref("Object.getOwnPropertyNames()")}}.
2. For each key, if no string with the same value has ever been visited, the [property descriptor is retrieved](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/getOwnPropertyDescriptor) and the property is only visited if it is enumerable. However, this property string will be marked as visited even if it's not enumerable.
3. Then, the current object is replaced with its prototype, and the process is repeated.
This means:
- Any property added to the currently visited object during iteration will not be visited, because all own properties of the current object have already been saved beforehand.
- If multiple objects in the prototype chain have a property with the same name, only the first one will be considered, and it is only visited if it's enumerable. If it is non-enumerable, no other properties with the same name further up the prototype chain will be visited, even if they are enumerable.
In general, it is best not to add, modify, or remove properties from the object during iteration, other than the property currently being visited. The spec explicitly allows the implementation to not follow the algorithm above in one of the following cases:
- The object's prototype chain is modified during iteration.
- A property is deleted from the object or its prototype chain during iteration.
- A property is added to the object's prototype chain during iteration.
- A property's enumerability is changed during iteration.
In these cases, implementations may behave differently from what you may expect, or even from each other.
### Array iteration and for...in
Array indexes are just enumerable properties with integer names and are otherwise identical to general object properties. The `for...in` loop will traverse all integer keys before traversing other keys, and in strictly increasing order, making the behavior of `for...in` close to normal array iteration. However, the `for...in` loop will return all enumerable properties, including those with nonβinteger names and those that are inherited. Unlike `for...of`, `for...in` uses property enumeration instead of the array's iterator. In [sparse arrays](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), `for...of` will visit the empty slots, but `for...in` will not.
It is better to use a {{jsxref("Statements/for", "for")}} loop with a numeric index, {{jsxref("Array.prototype.forEach()")}}, or the {{jsxref("Statements/for...of", "for...of")}} loop, because they will return the index as a number instead of a string, and also avoid non-index properties.
### Iterating over own properties only
If you only want to consider properties attached to the object itself, and not its prototypes, you can use one of the following techniques:
- {{jsxref("Object.keys()")}}
- {{jsxref("Object.getOwnPropertyNames()")}}
`Object.keys` will return a list of enumerable own string properties, while `Object.getOwnPropertyNames` will also contain non-enumerable ones.
Many JavaScript style guides and linters recommend against the use of `for...in`, because it iterates over the entire prototype chain which is rarely what one wants, and may be a confusion with the more widely-used `for...of` loop. `for...in` is most practically used for debugging purposes, being an easy way to check the properties of an object (by outputting to the console or otherwise). In situations where objects are used as ad hoc key-value pairs, `for...in` allows you check if any of those keys hold a particular value.
## Examples
### Using for...in
The `for...in` loop below iterates over all of the object's enumerable, non-symbol properties and logs a string of the property names and their values.
```js
const obj = { a: 1, b: 2, c: 3 };
for (const prop in obj) {
console.log(`obj.${prop} = ${obj[prop]}`);
}
// Logs:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"
```
### Iterating own properties
The following function illustrates the use of {{jsxref("Object.hasOwn()")}}: the inherited properties are not displayed.
```js
const triangle = { a: 1, b: 2, c: 3 };
function ColoredTriangle() {
this.color = "red";
}
ColoredTriangle.prototype = triangle;
const obj = new ColoredTriangle();
for (const prop in obj) {
if (Object.hasOwn(obj, prop)) {
console.log(`obj.${prop} = ${obj[prop]}`);
}
}
// Logs:
// "obj.color = red"
```
### Concurrent modification
> **Warning:** You should not write code like this yourself. It is only included here to illustrate the behavior of `for...in` in some corner cases.
Properties added to the current object during iteration are never visited:
```js
const obj = { a: 1, b: 2 };
for (const prop in obj) {
console.log(`obj.${prop} = ${obj[prop]}`);
obj.c = 3;
}
// Logs:
// obj.a = 1
// obj.b = 2
```
Shadowed properties are only visited once:
```js
const proto = { a: 1 };
const obj = { __proto__: proto, a: 2 };
for (const prop in obj) {
console.log(`obj.${prop} = ${obj[prop]}`);
}
// Logs:
// obj.a = 2
Object.defineProperty(obj, "a", { enumerable: false });
for (const prop in obj) {
console.log(`obj.${prop} = ${obj[prop]}`);
}
// Logs nothing, because the first "a" property visited is non-enumerable.
```
In addition, consider the following cases, where the behavior is unspecified, and implementations tend to diverge from the specified algorithm:
Changing the prototype during iteration:
```js
const obj = { a: 1, b: 2 };
for (const prop in obj) {
console.log(`obj.${prop} = ${obj[prop]}`);
Object.setPrototypeOf(obj, { c: 3 });
}
```
Deleting a property during iteration:
```js
const obj = { a: 1, b: 2, c: 3 };
// Deleting a property before it is visited
for (const prop in obj) {
console.log(`obj.${prop} = ${obj[prop]}`);
delete obj.c;
}
const obj2 = { a: 1, b: 2, c: 3 };
// Deleting a property after it is visited
for (const prop in obj2) {
console.log(`obj2.${prop} = ${obj2[prop]}`);
delete obj2.a;
}
```
Enumerable properties added to the prototype during iteration:
```js
const proto = {};
const obj = { __proto__: proto, a: 1, b: 2 };
for (const prop in obj) {
console.log(`obj.${prop} = ${obj[prop]}`);
proto.c = 3;
}
```
Changing the enumerability of a property during iteration:
```js
const obj = { a: 1, b: 2, c: 3 };
for (const prop in obj) {
console.log(`obj.${prop} = ${obj[prop]}`);
Object.defineProperty(obj, "c", { enumerable: false });
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Statements/for...of", "for...of")}}
- {{jsxref("Statements/for", "for")}}
- [Enumerability and ownership of properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
- {{jsxref("Object.getOwnPropertyNames()")}}
- {{jsxref("Object.hasOwn()")}}
- {{jsxref("Array.prototype.forEach()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/do...while/index.md | ---
title: do...while
slug: Web/JavaScript/Reference/Statements/do...while
page-type: javascript-statement
browser-compat: javascript.statements.do_while
---
{{jsSidebar("Statements")}}
The **`do...while`** statement creates a loop that executes a
specified statement until the test condition evaluates to false. The condition is
evaluated after executing the statement, resulting in the specified statement executing
at least once.
{{EmbedInteractiveExample("pages/js/statement-dowhile.html")}}
## Syntax
```js-nolint
do
statement
while (condition);
```
- `statement`
- : A statement that is executed at least once and is re-executed each time the
condition evaluates to true. To execute multiple statements within the loop, use a
{{jsxref("Statements/block", "block", "", 1)}} statement (`{ /* ... */ }`) to
group those statements.
- `condition`
- : An expression evaluated after each pass through the loop. If `condition`
[evaluates to true](/en-US/docs/Glossary/Truthy), the `statement` is re-executed. When
`condition` [evaluates to false](/en-US/docs/Glossary/Falsy), control passes to the statement following
the `do...while`.
Note: Use the {{jsxref("Statements/break", "break")}} statement to stop a loop before `condition` evaluates
to false.
## Examples
### Using `do...while`
In the following example, the `do...while` loop iterates at least once and
reiterates until `i` is no longer less than 5.
```js
let result = "";
let i = 0;
do {
i += 1;
result += `${i} `;
} while (i > 0 && i < 5);
// Despite i === 0 this will still loop as it starts off without the test
console.log(result);
```
### Using an assignment as a condition
In some cases, it can make sense to use an assignment as a condition, such as this:
```js
do {
// β¦
} while ((match = regexp.exec(str)));
```
But when you do, there are readability tradeoffs. The [`while`](/en-US/docs/Web/JavaScript/Reference/Statements/while) documentation has a [Using an assignment as a condition](/en-US/docs/Web/JavaScript/Reference/Statements/while#using_an_assignment_as_a_condition) section with our recommendations.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Statements/while", "while")}}
- {{jsxref("Statements/for", "for")}}
- {{jsxref("Statements/break", "break")}}
- {{jsxref("Statements/continue", "continue")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/class/index.md | ---
title: class
slug: Web/JavaScript/Reference/Statements/class
page-type: javascript-statement
browser-compat: javascript.statements.class
---
{{jsSidebar("Statements")}}
The **`class`** declaration creates a {{Glossary("binding")}} of a new [class](/en-US/docs/Web/JavaScript/Reference/Classes) to a given name.
You can also define classes using the [`class` expression](/en-US/docs/Web/JavaScript/Reference/Operators/class).
{{EmbedInteractiveExample("pages/js/statement-class.html")}}
## Syntax
```js-nolint
class name {
// class body
}
class name extends otherName {
// class body
}
```
## Description
The class body of a class declaration is executed in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode). The `class` declaration is very similar to {{jsxref("Statements/let", "let")}}:
- `class` declarations are scoped to blocks as well as functions.
- `class` declarations can only be accessed after the place of declaration is reached (see [temporal dead zone](/en-US/docs/Web/JavaScript/Reference/Statements/let#temporal_dead_zone_tdz)). For this reason, `class` declarations are commonly regarded as [non-hoisted](/en-US/docs/Glossary/Hoisting) (unlike [function declarations](/en-US/docs/Web/JavaScript/Reference/Statements/function)).
- `class` declarations do not create properties on {{jsxref("globalThis")}} when declared at the top level of a script (unlike [function declarations](/en-US/docs/Web/JavaScript/Reference/Statements/function)).
- `class` declarations cannot be [redeclared](/en-US/docs/Web/JavaScript/Reference/Statements/let#redeclarations) by any other declaration in the same scope.
Outside the class body, `class` declarations can be re-assigned like `let`, but you should avoid doing so. Within the class body, the binding is constant like `const`.
```js
class Foo {
static {
Foo = 1; // TypeError: Assignment to constant variable.
}
}
class Foo2 {
bar = (Foo2 = 1); // TypeError: Assignment to constant variable.
}
class Foo3 {}
Foo3 = 1;
console.log(Foo3); // 1
```
## Examples
### A simple class declaration
In the following example, we first define a class named `Rectangle`, then extend it to create a class named `FilledRectangle`.
Note that `super()`, used in the `constructor`, can only be used in constructors, and _must_ be called _before_ the `this` keyword can be used.
```js
class Rectangle {
constructor(height, width) {
this.name = "Rectangle";
this.height = height;
this.width = width;
}
}
class FilledRectangle extends Rectangle {
constructor(height, width, color) {
super(height, width);
this.name = "Filled rectangle";
this.color = color;
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`function`](/en-US/docs/Web/JavaScript/Reference/Statements/function)
- [`class` expression](/en-US/docs/Web/JavaScript/Reference/Operators/class)
- [Classes](/en-US/docs/Web/JavaScript/Reference/Classes)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/for-await...of/index.md | ---
title: for await...of
slug: Web/JavaScript/Reference/Statements/for-await...of
page-type: javascript-statement
browser-compat: javascript.statements.for_await_of
---
{{jsSidebar("Statements")}}
The **`for await...of`** statement creates a loop iterating over [async iterable objects](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) as well as [sync iterables](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol). This statement can only be used in contexts where [`await`](/en-US/docs/Web/JavaScript/Reference/Operators/await) can be used, which includes inside an [async function](/en-US/docs/Web/JavaScript/Reference/Statements/async_function) body and in a [module](/en-US/docs/Web/JavaScript/Guide/Modules).
{{EmbedInteractiveExample("pages/js/statement-forawaitof.html", "taller")}}
## Syntax
```js-nolint
for await (variable of iterable)
statement
```
- `variable`
- : Receives a value from the sequence on each iteration. May be either a declaration with [`const`](/en-US/docs/Web/JavaScript/Reference/Statements/const), [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let), or [`var`](/en-US/docs/Web/JavaScript/Reference/Statements/var), or an [assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Assignment) target (e.g. a previously declared variable, an object property, or a [destructuring assignment pattern](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)). Variables declared with `var` are not local to the loop, i.e. they are in the same scope the `for await...of` loop is in.
- `iterable`
- : An async iterable or sync iterable. The source of the sequence of values on which the loop operates.
- `statement`
- : A statement to be executed on every iteration. May reference `variable`. You can use a [block statement](/en-US/docs/Web/JavaScript/Reference/Statements/block) to execute multiple statements.
## Description
When a `for await...of` loop iterates over an iterable, it first gets the iterable's [`[@@asyncIterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/asyncIterator) method and calls it, which returns an [async iterator](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols). If the `@asyncIterator` method does not exist, it then looks for an [`[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator) method, which returns a [sync iterator](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol). The sync iterator returned is then wrapped into an async iterator by wrapping every object returned from the `next()`, `return()`, and `throw()` methods into a resolved or rejected promise, with the `value` property resolved if it's also a promise. The loop then repeatedly calls the final async iterator's [`next()`](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol) method and [awaits](/en-US/docs/Web/JavaScript/Reference/Operators/await) the returned promise, producing the sequence of values to be assigned to `variable`.
If the `for await...of` loop exited early (e.g. a `break` statement is encountered or an error is thrown), the [`return()`](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol) method of the iterator is called to perform any cleanup. The returned promise is awaited before the loop exits.
`for await...of` generally functions the same as the [`for...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for...of) loop and shares many of the same syntax and semantics. There are a few differences:
- `for await...of` works on both sync and async iterables, while `for...of` only works on sync iterables.
- `for await...of` can only be used in contexts where [`await`](/en-US/docs/Web/JavaScript/Reference/Operators/await) can be used, which includes inside an [async function](/en-US/docs/Web/JavaScript/Reference/Statements/async_function) body and in a [module](/en-US/docs/Web/JavaScript/Guide/Modules). Even when the iterable is sync, the loop still awaits the return value for every iteration, leading to slower execution due to repeated promise unwrapping.
- If the `iterable` is a sync iterable that yields promises, `for await...of` would produce a sequence of resolved values, while `for...of` would produce a sequence of promises. (However, beware of error handling and cleanup β see [Iterating over sync iterables and generators](#iterating_over_sync_iterables_and_generators))
- For `for await...of`, the `variable` can be the identifier `async` (e.g. `for await (async of foo)`); `for...of` forbids this case.
## Examples
### Iterating over async iterables
You can also iterate over an object that explicitly implements async iterable protocol:
```js
const LIMIT = 3;
const asyncIterable = {
[Symbol.asyncIterator]() {
let i = 0;
return {
next() {
const done = i === LIMIT;
const value = done ? undefined : i++;
return Promise.resolve({ value, done });
},
return() {
// This will be reached if the consumer called 'break' or 'return' early in the loop.
return { done: true };
},
};
},
};
(async () => {
for await (const num of asyncIterable) {
console.log(num);
}
})();
// 0
// 1
// 2
```
### Iterating over async generators
Since the return values of async generator functions conform to the async iterable protocol,
they can be looped using `for await...of`.
```js
async function* asyncGenerator() {
let i = 0;
while (i < 3) {
yield i++;
}
}
(async () => {
for await (const num of asyncGenerator()) {
console.log(num);
}
})();
// 0
// 1
// 2
```
For a more concrete example of iterating over an async generator using `for await...of`, consider iterating over data from an API.
This example first creates an async iterable for a stream of data, then uses it to find the size of the response from the API.
```js
async function* streamAsyncIterable(stream) {
const reader = stream.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) return;
yield value;
}
} finally {
reader.releaseLock();
}
}
// Fetches data from URL and calculates response size using the async generator.
async function getResponseSize(url) {
const response = await fetch(url);
// Will hold the size of the response, in bytes.
let responseSize = 0;
// The for-await-of loop. Async iterates over each portion of the response.
for await (const chunk of streamAsyncIterable(response.body)) {
// Incrementing the total response length.
responseSize += chunk.length;
}
console.log(`Response Size: ${responseSize} bytes`); // "Response Size: 1071472"
return responseSize;
}
getResponseSize("https://jsonplaceholder.typicode.com/photos");
```
### Iterating over sync iterables and generators
`for await...of` loop also consumes sync iterables and generators. In that case it internally awaits emitted values before assign them to the loop control variable.
```js
function* generator() {
yield 0;
yield 1;
yield Promise.resolve(2);
yield Promise.resolve(3);
yield 4;
}
(async () => {
for await (const num of generator()) {
console.log(num);
}
})();
// 0
// 1
// 2
// 3
// 4
// compare with for-of loop:
for (const numOrPromise of generator()) {
console.log(numOrPromise);
}
// 0
// 1
// Promise { 2 }
// Promise { 3 }
// 4
```
> **Note:** Be aware of yielding rejected promises from a sync generator. In such case, `for await...of` throws when consuming the rejected promise and DOESN'T CALL `finally` blocks within that generator. This can be undesirable if you need to free some allocated resources with `try/finally`.
```js
function* generatorWithRejectedPromises() {
try {
yield 0;
yield 1;
yield Promise.resolve(2);
yield Promise.reject(3);
yield 4;
throw 5;
} finally {
console.log("called finally");
}
}
(async () => {
try {
for await (const num of generatorWithRejectedPromises()) {
console.log(num);
}
} catch (e) {
console.log("caught", e);
}
})();
// 0
// 1
// 2
// caught 3
// compare with for-of loop:
try {
for (const numOrPromise of generatorWithRejectedPromises()) {
console.log(numOrPromise);
}
} catch (e) {
console.log("caught", e);
}
// 0
// 1
// Promise { 2 }
// Promise { <rejected> 3 }
// 4
// caught 5
// called finally
```
To make `finally` blocks of a sync generator always called, use the appropriate form of the loop β `for await...of` for the async generator and `for...of` for the sync one β and await yielded promises explicitly inside the loop.
```js
(async () => {
try {
for (const numOrPromise of generatorWithRejectedPromises()) {
console.log(await numOrPromise);
}
} catch (e) {
console.log("caught", e);
}
})();
// 0
// 1
// 2
// caught 3
// called finally
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Symbol.asyncIterator")}}
- {{jsxref("Statements/for...of", "for...of")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/import/index.md | ---
title: import
slug: Web/JavaScript/Reference/Statements/import
page-type: javascript-statement
browser-compat: javascript.statements.import
---
{{jsSidebar("Statements")}}
The static **`import`** declaration is used to import read-only live {{Glossary("binding", "bindings")}} which are [exported](/en-US/docs/Web/JavaScript/Reference/Statements/export) by another module. The imported bindings are called _live bindings_ because they are updated by the module that exported the binding, but cannot be re-assigned by the importing module.
In order to use the `import` declaration in a source file, the file must be interpreted by the runtime as a [module](/en-US/docs/Web/JavaScript/Guide/Modules). In HTML, this is done by adding `type="module"` to the {{HTMLElement("script")}} tag. Modules are automatically interpreted in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode).
There is also a function-like dynamic [`import()`](/en-US/docs/Web/JavaScript/Reference/Operators/import), which does not require scripts of `type="module"`.
## Syntax
```js-nolint
import defaultExport from "module-name";
import * as name from "module-name";
import { export1 } from "module-name";
import { export1 as alias1 } from "module-name";
import { default as alias } from "module-name";
import { export1, export2 } from "module-name";
import { export1, export2 as alias2, /* β¦ */ } from "module-name";
import { "string name" as alias } from "module-name";
import defaultExport, { export1, /* β¦ */ } from "module-name";
import defaultExport, * as name from "module-name";
import "module-name";
```
- `defaultExport`
- : Name that will refer to the default export from the module. Must be a valid JavaScript identifier.
- `module-name`
- : The module to import from. The evaluation of the specifier is host-specified. This is often a relative or absolute URL to the `.js` file containing the module. In Node, extension-less imports often refer to packages in `node_modules`. Certain bundlers may permit importing files without extensions; check your environment. Only single quoted and double quoted Strings are allowed.
- `name`
- : Name of the module object that will be used as a kind of namespace when referring to the imports. Must be a valid JavaScript identifier.
- `exportN`
- : Name of the exports to be imported. The name can be either an identifier or a string literal, depending on what `module-name` declares to export. If it is a string literal, it must be aliased to a valid identifier.
- `aliasN`
- : Names that will refer to the named imports. Must be a valid JavaScript identifier.
## Description
`import` declarations can only be present in modules, and only at the top-level (i.e. not inside blocks, functions, etc.). If an `import` declaration is encountered in non-module contexts (for example, `<script>` tags without `type="module"`, `eval`, `new Function`, which all have "script" or "function body" as parsing goals), a `SyntaxError` is thrown. To load modules in non-module contexts, use the [dynamic import](/en-US/docs/Web/JavaScript/Reference/Operators/import) syntax instead.
All imported bindings cannot be in the same scope as any other declaration, including {{jsxref("Statements/let", "let")}}, {{jsxref("Statements/const", "const")}}, {{jsxref("Statements/class", "class")}}, {{jsxref("Statements/function", "function")}}, {{jsxref("Statements/var", "var")}}, and `import` declaration.
`import` declarations are designed to be syntactically rigid (for example, only string literal specifiers, only permitted at the top-level, all bindings must be identifiers), which allows modules to be statically analyzed and linked before getting evaluated. This is the key to making modules asynchronous by nature, powering features like [top-level await](/en-US/docs/Web/JavaScript/Guide/Modules#top_level_await).
### Forms of import declarations
There are four forms of `import` declarations:
- [Named import](#named_import): `import { export1, export2 } from "module-name";`
- [Default import](#default_import): `import defaultExport from "module-name";`
- [Namespace import](#namespace_import): `import * as name from "module-name";`
- [Side effect import](#import_a_module_for_its_side_effects_only): `import "module-name";`
Below are examples to clarify the syntax.
#### Named import
Given a value named `myExport` which has been exported from the module `my-module` either implicitly as `export * from "another.js"` or explicitly using the {{jsxref("Statements/export", "export")}} statement, this inserts `myExport` into the current scope.
```js
import { myExport } from "/modules/my-module.js";
```
You can import multiple names from the same module.
```js
import { foo, bar } from "/modules/my-module.js";
```
You can rename an export when importing it. For example, this inserts `shortName` into the current scope.
```js
import { reallyReallyLongModuleExportName as shortName } from "/modules/my-module.js";
```
A module may also export a member as a string literal which is not a valid identifier, in which case you must alias it in order to use it in the current module.
```js
// /modules/my-module.js
const a = 1;
export { a as "a-b" };
```
```js
import { "a-b" as a } from "/modules/my-module.js";
```
> **Note:** `import { x, y } from "mod"` is not equivalent to `import defaultExport from "mod"` and then destructuring `x` and `y` from `defaultExport`. Named and default imports are distinct syntaxes in JavaScript modules.
#### Default import
Default exports need to be imported with the corresponding default import syntax. The simplest version directly imports the default:
```js
import myDefault from "/modules/my-module.js";
```
Since the default export doesn't explicitly specify a name, you can give the identifier any name you like.
It is also possible to specify a default import with namespace imports or named imports. In such cases, the default import will have to be declared first. For instance:
```js
import myDefault, * as myModule from "/modules/my-module.js";
// myModule.default and myDefault point to the same binding
```
or
```js
import myDefault, { foo, bar } from "/modules/my-module.js";
```
Importing a name called `default` has the same effect as a default import. It is necessary to alias the name because `default` is a reserved word.
```js
import { default as myDefault } from "/modules/my-module.js";
```
#### Namespace import
The following code inserts `myModule` into the current scope, containing all the exports from the module located at `/modules/my-module.js`.
```js
import * as myModule from "/modules/my-module.js";
```
Here, `myModule` represents a _namespace_ object which contains all exports as properties. For example, if the module imported above includes an export `doAllTheAmazingThings()`, you would call it like this:
```js
myModule.doAllTheAmazingThings();
```
`myModule` is a [sealed](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isSealed) object with [`null` prototype](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects). The default export available as a key called `default`. For more information, see [module namespace object](/en-US/docs/Web/JavaScript/Reference/Operators/import#module_namespace_object).
> **Note:** JavaScript does not have wildcard imports like `import * from "module-name"`, because of the high possibility of name conflicts.
#### Import a module for its side effects only
Import an entire module for side effects only, without importing anything. This runs
the module's global code, but doesn't actually import any values.
```js
import "/modules/my-module.js";
```
This is often used for [polyfills](/en-US/docs/Glossary/Polyfill), which mutate the global variables.
### Hoisting
Import declarations are [hoisted](/en-US/docs/Glossary/Hoisting). In this case, that means that the identifiers the imports introduce are available in the entire module scope, and their side effects are produced before the rest of the module's code runs.
```js
myModule.doAllTheAmazingThings(); // myModule.doAllTheAmazingThings is imported by the next line
import * as myModule from "/modules/my-module.js";
```
## Examples
### Standard Import
In this example, we create a re-usable module that exports a function to get all primes within a given range.
```js
// getPrimes.js
/**
* Returns a list of prime numbers that are smaller than `max`.
*/
export function getPrimes(max) {
const isPrime = Array.from({ length: max }, () => true);
isPrime[0] = isPrime[1] = false;
isPrime[2] = true;
for (let i = 2; i * i < max; i++) {
if (isPrime[i]) {
for (let j = i ** 2; j < max; j += i) {
isPrime[j] = false;
}
}
}
return [...isPrime.entries()]
.filter(([, isPrime]) => isPrime)
.map(([number]) => number);
}
```
```js
import { getPrimes } from "/modules/getPrimes.js";
console.log(getPrimes(10)); // [2, 3, 5, 7]
```
### Imported values can only be modified by the exporter
The identifier being imported is a _live binding_, because the module exporting it may re-assign it and the imported value would change. However, the module importing it cannot re-assign it. Still, any module holding an exported object can mutate the object, and the mutated value can be observed by all other modules importing the same value.
You can also observe the new value through the [module namespace object](/en-US/docs/Web/JavaScript/Reference/Operators/import#module_namespace_object).
```js
// my-module.js
export let myValue = 1;
setTimeout(() => {
myValue = 2;
}, 500);
```
```js
// main.js
import { myValue } from "/modules/my-module.js";
import * as myModule from "/modules/my-module.js";
console.log(myValue); // 1
console.log(myModule.myValue); // 1
setTimeout(() => {
console.log(myValue); // 2; my-module has updated its value
console.log(myModule.myValue); // 2
myValue = 3; // TypeError: Assignment to constant variable.
// The importing module can only read the value but can't re-assign it.
}, 1000);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Statements/export", "export")}}
- [`import()`](/en-US/docs/Web/JavaScript/Reference/Operators/import)
- [`import.meta`](/en-US/docs/Web/JavaScript/Reference/Operators/import.meta)
- [Previewing ES6 Modules and more from ES2015, ES2016 and beyond](https://blogs.windows.com/msedgedev/2016/05/17/es6-modules-and-beyond/) on blogs.windows.com (2016)
- [ES6 in Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules/) on hacks.mozilla.org (2015)
- [ES modules: A cartoon deep-dive](https://hacks.mozilla.org/2018/03/es-modules-a-cartoon-deep-dive/) on hacks.mozilla.org (2018)
- [Exploring JS, Ch.16: Modules](https://exploringjs.com/es6/ch_modules.html) by Dr. Axel Rauschmayer
- [Export and Import](https://javascript.info/import-export) on javascript.info
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/let/index.md | ---
title: let
slug: Web/JavaScript/Reference/Statements/let
page-type: javascript-statement
browser-compat: javascript.statements.let
---
{{jsSidebar("Statements")}}
The **`let`** declaration declares re-assignable, block-scoped local variables, optionally initializing each to a value.
{{EmbedInteractiveExample("pages/js/statement-let.html")}}
## Syntax
```js-nolint
let name1;
let name1 = value1;
let name1 = value1, name2 = value2;
let name1, name2 = value2;
let name1 = value1, name2, /* β¦, */ nameN = valueN;
```
### Parameters
- `nameN`
- : The name of the variable to declare. Each must be a legal JavaScript [identifier](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers) or a [destructuring binding pattern](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment).
- `valueN` {{optional_inline}}
- : Initial value of the variable. It can be any legal expression. Default value is `undefined`.
## Description
The scope of a variable declared with `let` is one of the following curly-brace-enclosed syntaxes that most closely contains the `let` declaration:
- [Block](/en-US/docs/Web/JavaScript/Reference/Statements/block) statement
- {{jsxref("Statements/switch", "switch")}} statement
- {{jsxref("Statements/try...catch", "try...catch")}} statement
- Body of [one of the `for` statements](/en-US/docs/Web/JavaScript/Reference/Statements#iterations), if the `let` is in the header of the statement
- Function body
- [Static initialization block](/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks)
Or if none of the above applies:
- The current [module](/en-US/docs/Web/JavaScript/Guide/Modules), for code running in module mode
- The global scope, for code running in script mode.
Compared with {{jsxref("Statements/var", "var")}}, `let` declarations have the following differences:
- `let` declarations are scoped to blocks as well as functions.
- `let` declarations can only be accessed after the place of declaration is reached (see [temporal dead zone](#temporal_dead_zone_tdz)). For this reason, `let` declarations are commonly regarded as [non-hoisted](/en-US/docs/Glossary/Hoisting).
- `let` declarations do not create properties on {{jsxref("globalThis")}} when declared at the top level of a script.
- `let` declarations cannot be [redeclared](#redeclarations) by any other declaration in the same scope.
- `let` begins [_declarations_, not _statements_](/en-US/docs/Web/JavaScript/Reference/Statements#difference_between_statements_and_declarations). That means you cannot use a lone `let` declaration as the body of a block (which makes sense, since there's no way to access the variable).
```js-nolint example-bad
if (true) let a = 1; // SyntaxError: Lexical declaration cannot appear in a single-statement context
```
Note that `let` is allowed as an identifier name when declared with `var` or `function` in [non-strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode), but you should avoid using `let` as an identifier name to prevent unexpected syntax ambiguities.
Many style guides (including [MDN's](/en-US/docs/MDN/Writing_guidelines/Writing_style_guide/Code_style_guide/JavaScript#variable_declarations)) recommend using {{jsxref("Statements/const", "const")}} over `let` whenever a variable is not reassigned in its scope. This makes the intent clear that a variable's type (or value, in the case of a primitive) can never change. Others may prefer `let` for non-primitives that are mutated.
The list that follows the `let` keyword is called a _{{Glossary("binding")}} list_ and is separated by commas, where the commas are _not_ [comma operators](/en-US/docs/Web/JavaScript/Reference/Operators/Comma_operator) and the `=` signs are _not_ [assignment operators](/en-US/docs/Web/JavaScript/Reference/Operators/Assignment). Initializers of later variables can refer to earlier variables in the list.
### Temporal dead zone (TDZ)
A variable declared with `let`, `const`, or `class` is said to be in a "temporal dead zone" (TDZ) from the start of the block until code execution reaches the place where the variable is declared and initialized.
While inside the TDZ, the variable has not been initialized with a value, and any attempt to access it will result in a {{jsxref("ReferenceError")}}. The variable is initialized with a value when execution reaches the place in the code where it was declared. If no initial value was specified with the variable declaration, it will be initialized with a value of `undefined`.
This differs from {{jsxref("Statements/var", "var", "hoisting")}} variables, which will return a value of `undefined` if they are accessed before they are declared. The code below demonstrates the different result when `let` and `var` are accessed in code before the place where they are declared.
```js example-bad
{
// TDZ starts at beginning of scope
console.log(bar); // "undefined"
console.log(foo); // ReferenceError: Cannot access 'foo' before initialization
var bar = 1;
let foo = 2; // End of TDZ (for foo)
}
```
The term "temporal" is used because the zone depends on the order of execution (time) rather than the order in which the code is written (position). For example, the code below works because, even though the function that uses the `let` variable appears before the variable is declared, the function is _called_ outside the TDZ.
```js
{
// TDZ starts at beginning of scope
const func = () => console.log(letVar); // OK
// Within the TDZ letVar access throws `ReferenceError`
let letVar = 3; // End of TDZ (for letVar)
func(); // Called outside TDZ!
}
```
Using the `typeof` operator for a `let` variable in its TDZ will throw a {{jsxref("ReferenceError")}}:
```js example-bad
typeof i; // ReferenceError: Cannot access 'i' before initialization
let i = 10;
```
This differs from using `typeof` for undeclared variables, and variables that hold a value of `undefined`:
```js
console.log(typeof undeclaredVariable); // "undefined"
```
> **Note:** `let` and `const` declarations are only processed when the current script gets processed. If you have two `<script>` elements running in script mode within one HTML, the first script is not subject to the TDZ restrictions for top-level `let` or `const` variables declared in the second script, although if you declare a `let` or `const` variable in the first script, declaring it again in the second script will cause a [redeclaration error](#redeclarations).
### Redeclarations
`let` declarations cannot be in the same scope as any other declaration, including `let`, {{jsxref("Statements/const", "const")}}, {{jsxref("Statements/class", "class")}}, {{jsxref("Statements/function", "function")}}, {{jsxref("Statements/var", "var")}}, and {{jsxref("Statements/import", "import")}} declaration.
```js-nolint example-bad
{
let foo;
let foo; // SyntaxError: Identifier 'foo' has already been declared
}
```
A `let` declaration within a function's body cannot have the same name as a parameter. A `let` declaration within a `catch` block cannot have the same name as the `catch`-bound identifier.
```js-nolint example-bad
function foo(a) {
let a = 1; // SyntaxError: Identifier 'a' has already been declared
}
try {
} catch (e) {
let e; // SyntaxError: Identifier 'e' has already been declared
}
```
If you're experimenting in a REPL, such as the Firefox web console (**Tools** > **Web Developer** > **Web Console**), and you run two `let` declarations with the same name in two separate inputs, you may get the same re-declaration error. See further discussion of this issue in [Firefox bug 1580891](https://bugzil.la/1580891). The Chrome console allows `let` re-declarations between different REPL inputs.
You may encounter errors in {{jsxref("Statements/switch", "switch")}} statements because there is only one block.
```js-nolint example-bad
let x = 1;
switch (x) {
case 0:
let foo;
break;
case 1:
let foo; // SyntaxError: Identifier 'foo' has already been declared
break;
}
```
To avoid the error, wrap each `case` in a new block statement.
```js
let x = 1;
switch (x) {
case 0: {
let foo;
break;
}
case 1: {
let foo;
break;
}
}
```
## Examples
### Scoping rules
Variables declared by `let` have their scope in the block for which they are declared, as well as in any contained sub-blocks. In this way, `let` works very much like `var`. The main difference is that the scope of a `var` variable is the entire enclosing function:
```js
function varTest() {
var x = 1;
{
var x = 2; // same variable!
console.log(x); // 2
}
console.log(x); // 2
}
function letTest() {
let x = 1;
{
let x = 2; // different variable
console.log(x); // 2
}
console.log(x); // 1
}
```
At the top level of programs and functions, `let`, unlike `var`, does not create a property on the global object. For example:
```js
var x = "global";
let y = "global";
console.log(this.x); // "global"
console.log(this.y); // undefined
```
### TDZ combined with lexical scoping
The following code results in a `ReferenceError` at the line shown:
```js example-bad
function test() {
var foo = 33;
if (foo) {
let foo = foo + 55; // ReferenceError
}
}
test();
```
The `if` block is evaluated because the outer `var foo` has a value. However due to lexical scoping this value is not available inside the block: the identifier `foo` _inside_ the `if` block is the `let foo`. The expression `foo + 55` throws a `ReferenceError` because initialization of `let foo` has not completed β it is still in the temporal dead zone.
This phenomenon can be confusing in a situation like the following. The instruction `let n of n.a` is already inside the scope of the `for...of` loop's block. So, the identifier `n.a` is resolved to the property `a` of the `n` object located in the first part of the instruction itself (`let n`). This is still in the temporal dead zone as its declaration statement has not been reached and terminated.
```js example-bad
function go(n) {
// n here is defined!
console.log(n); // { a: [1, 2, 3] }
for (let n of n.a) {
// ^ ReferenceError
console.log(n);
}
}
go({ a: [1, 2, 3] });
```
### Other situations
When used inside a block, `let` limits the variable's scope to that block. Note the difference between `var`, whose scope is inside the function where it is declared.
```js
var a = 1;
var b = 2;
{
var a = 11; // the scope is global
let b = 22; // the scope is inside the block
console.log(a); // 11
console.log(b); // 22
}
console.log(a); // 11
console.log(b); // 2
```
However, this combination of `var` and `let` declarations below is a {{jsxref("SyntaxError")}} because `var` not being block-scoped, leading to them being in the same scope. This results in an implicit re-declaration of the variable.
```js-nolint example-bad
let x = 1;
{
var x = 2; // SyntaxError for re-declaration
}
```
### Declaration with destructuring
The left-hand side of each `=` can also be a binding pattern. This allows creating multiple variables at once.
```js
const result = /(a+)(b+)(c+)/.exec("aaabcc");
let [, a, b, c] = result;
console.log(a, b, c); // "aaa" "b" "cc"
```
For more information, see [Destructuring assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Statements/var", "var")}}
- {{jsxref("Statements/const", "const")}}
- [Hoisting](/en-US/docs/Glossary/Hoisting)
- [ES6 In Depth: `let` and `const`](https://hacks.mozilla.org/2015/07/es6-in-depth-let-and-const/) on hacks.mozilla.org (2015)
- [Breaking changes in `let` and `const` in Firefox 44](https://blog.mozilla.org/addons/2015/10/14/breaking-changes-let-const-firefox-nightly-44/) on blog.mozilla.org (2015)
- [You Don't Know JS: Scope & Closures, Ch.3: Function vs. Block Scope](https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/scope%20%26%20closures/ch3.md) by Kyle Simpson
- [What is the Temporal Dead Zone?](https://stackoverflow.com/questions/33198849/what-is-the-temporal-dead-zone/33198850) on Stack Overflow
- [What is the difference between using `let` and `var`?](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var) on Stack Overflow
- [Why was the name 'let' chosen for block-scoped variable declarations in JavaScript?](https://stackoverflow.com/questions/37916940/why-was-the-name-let-chosen-for-block-scoped-variable-declarations-in-javascri) on Stack Overflow
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/expression_statement/index.md | ---
title: Expression statement
slug: Web/JavaScript/Reference/Statements/Expression_statement
page-type: javascript-statement
spec-urls: https://tc39.es/ecma262/multipage/ecmascript-language-statements-and-declarations.html#sec-expression-statement
---
{{jsSidebar("Statements")}}
An **expression statement** is an expression used in a place where a statement is expected. The expression is evaluated and its result is discarded β therefore, it makes sense only for expressions that have side effects, such as executing a function or updating a variable.
## Syntax
```js-nolint
expression;
```
- `expression`
- : An arbitrary [expression](/en-US/docs/Web/JavaScript/Reference/Operators) to be evaluated. There are [certain expressions](#forbidden_expressions) that may be ambiguous with other statements and are thus forbidden.
## Description
Apart from the [dedicated statement syntaxes](/en-US/docs/Web/JavaScript/Reference/Statements), you can also use almost any [expression](/en-US/docs/Web/JavaScript/Reference/Operators) as a statement on its own. The expression statement syntax requires a semicolon at the end, but the [automatic semicolon insertion](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#automatic_semicolon_insertion) process may insert one for you if the lack of a semicolon results in invalid syntax.
Because the expression is evaluated and then discarded, the result of the expression is not available. Therefore, the expression must have some side effect for it to be useful. Expression statements are commonly:
- Function calls (`console.log("Hello");`, `[1, 2, 3].forEach((i) => console.log(i));`)
- [Tagged template literals](/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates)
- [Assignment expressions](/en-US/docs/Web/JavaScript/Reference/Operators#assignment_operators), including compound assignments
- [Increment and decrement operators](/en-US/docs/Web/JavaScript/Reference/Operators#increment_and_decrement)
- [`delete`](/en-US/docs/Web/JavaScript/Reference/Operators/delete)
- [`import()`](/en-US/docs/Web/JavaScript/Reference/Operators/import)
- [`yield`](/en-US/docs/Web/JavaScript/Reference/Operators/yield) and [`yield*`](/en-US/docs/Web/JavaScript/Reference/Operators/yield*)
Others may also have side effects if they invoke [getters](/en-US/docs/Web/JavaScript/Reference/Functions/get) or trigger [type coercions](/en-US/docs/Web/JavaScript/Data_structures#type_coercion).
### Forbidden expressions
In order for an expression to be used as a statement, it must not be ambiguous with other statement syntaxes. Therefore, the expression must not start with any of the following tokens:
- `function`: which would be a [`function` declaration](/en-US/docs/Web/JavaScript/Reference/Statements/function) or [`function*` declaration](/en-US/docs/Web/JavaScript/Reference/Statements/function*), not a [`function` expression](/en-US/docs/Web/JavaScript/Reference/Operators/function) or [`function*` expression](/en-US/docs/Web/JavaScript/Reference/Operators/function*)
- `async function`: which would be an [`async function` declaration](/en-US/docs/Web/JavaScript/Reference/Statements/async_function) or [`async function*` declaration](/en-US/docs/Web/JavaScript/Reference/Statements/async_function*), not an [`async function` expression](/en-US/docs/Web/JavaScript/Reference/Operators/async_function) or [`async function*` expression](/en-US/docs/Web/JavaScript/Reference/Operators/async_function*)
- `class`: which would be a [`class` declaration](/en-US/docs/Web/JavaScript/Reference/Statements/class), not a [`class` expression](/en-US/docs/Web/JavaScript/Reference/Operators/class)
- `let[`: which would be a [`let` declaration](/en-US/docs/Web/JavaScript/Reference/Statements/let) with [array destructuring](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), not a [property accessor](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors) on a variable called `let` (`let` can only be an identifier in [non-strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode#extra_reserved_words))
- `{`: which would be a [block statement](/en-US/docs/Web/JavaScript/Reference/Statements/block), not an [object literal](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer)
Therefore, all of the following are invalid:
```js-nolint example-bad
function foo() {
console.log("foo");
}(); // SyntaxError: Unexpected token '('
// For some reason, you have a variable called `let`
var let = [1, 2, 3];
let[0] = 4; // SyntaxError: Invalid destructuring assignment target
{
foo: 1,
bar: 2, // SyntaxError: Unexpected token ':'
};
```
More dangerously, sometimes the code happens to be valid syntax, but is not what you intend.
```js-nolint example-bad
// For some reason, you have a variable called `let`
var let = [1, 2, 3];
function setIndex(index, value) {
if (index >= 0) {
// Intend to assign to the array `let`, but instead creates an extra variable!
let[index] = value;
}
}
setIndex(0, [1, 2]);
console.log(let); // [1, 2, 3]
// This is not an object literal, but a block statement,
// where `foo` is a label and `1` is an expression statement.
// This often happens in the console
{ foo: 1 };
```
To avoid these problems, you can use parentheses, so that the statement is unambiguously an expression statement.
```js example-good
(function foo() {
console.log("foo");
})();
```
## Examples
### Avoiding control flow statements
You can avoid almost all use of control flow statements using expression statements. For example, `if...else` can be replaced with [ternary operators](/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator) and [logical operators](/en-US/docs/Web/JavaScript/Reference/Operators#binary_logical_operators). Iterative statements like `for` or `for...of` can be replaced with [array methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#instance_methods).
```js
// Using control flow statements
function range(start, end) {
if (start > end) {
[start, end] = [end, start];
}
const result = [];
for (let i = start; i < end; i++) {
result.push(i);
}
return result;
}
// Using expression statements
function range2(start, end) {
start > end && ([start, end] = [end, start]);
return Array.from({ length: end - start }, (_, i) => start + i);
}
```
> **Warning:** This only demonstrates a capability of the language. Excessive use of expression statements as a substitute for control-flow statements can make code much less readable.
## Specifications
{{Specifications}}
## See also
- [Statements and declarations](/en-US/docs/Web/JavaScript/Reference/Statements)
- [Expressions and operators](/en-US/docs/Web/JavaScript/Reference/Operators)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/for...of/index.md | ---
title: for...of
slug: Web/JavaScript/Reference/Statements/for...of
page-type: javascript-statement
browser-compat: javascript.statements.for_of
---
{{jsSidebar("Statements")}}
The **`for...of`** statement executes a loop that operates on a sequence of values sourced from an [iterable object](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol). Iterable objects include instances of built-ins such as {{jsxref("Array")}}, {{jsxref("String")}}, {{jsxref("TypedArray")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{domxref("NodeList")}} (and other DOM collections), as well as the {{jsxref("Functions/arguments", "arguments")}} object, [generators](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator) produced by [generator functions](/en-US/docs/Web/JavaScript/Reference/Statements/function*), and user-defined iterables.
{{EmbedInteractiveExample("pages/js/statement-forof.html")}}
## Syntax
```js-nolint
for (variable of iterable)
statement
```
- `variable`
- : Receives a value from the sequence on each iteration. May be either a declaration with [`const`](/en-US/docs/Web/JavaScript/Reference/Statements/const), [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let), or [`var`](/en-US/docs/Web/JavaScript/Reference/Statements/var), or an [assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Assignment) target (e.g. a previously declared variable, an object property, or a [destructuring assignment pattern](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)). Variables declared with `var` are not local to the loop, i.e. they are in the same scope the `for...of` loop is in.
- `iterable`
- : An iterable object. The source of the sequence of values on which the loop operates.
- `statement`
- : A statement to be executed on every iteration. May reference `variable`. You can use a [block statement](/en-US/docs/Web/JavaScript/Reference/Statements/block) to execute multiple statements.
## Description
A `for...of` loop operates on the values sourced from an iterable one by one in sequential order. Each operation of the loop on a value is called an _iteration_, and the loop is said to _iterate over the iterable_. Each iteration executes statements that may refer to the current sequence value.
When a `for...of` loop iterates over an iterable, it first calls the iterable's [`[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator) method, which returns an [iterator](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol), and then repeatedly calls the resulting iterator's [`next()`](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol) method to produce the sequence of values to be assigned to `variable`.
A `for...of` loop exits when the iterator has completed (the iterator's `next()` method returns an object containing `done: true`). You may also use control flow statements to change the normal control flow. [`break`](/en-US/docs/Web/JavaScript/Reference/Statements/break) exits the loop and goes to the first statement after the loop body, while [`continue`](/en-US/docs/Web/JavaScript/Reference/Statements/continue) skips the rest of the statements of the current iteration and proceeds to the next iteration.
If the `for...of` loop exited early (e.g. a `break` statement is encountered or an error is thrown), the [`return()`](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol) method of the iterator is called to perform any cleanup.
The `variable` part of `for...of` accepts anything that can come before the `=` operator. You can use {{jsxref("Statements/const", "const")}} to declare the variable as long as it's not reassigned within the loop body (it can change between iterations, because those are two separate variables). Otherwise, you can use {{jsxref("Statements/let", "let")}}.
```js
const iterable = [10, 20, 30];
for (let value of iterable) {
value += 1;
console.log(value);
}
// 11
// 21
// 31
```
> **Note:** Each iteration creates a new variable. Reassigning the variable inside the loop body does not affect the original value in the iterable (an array, in this case).
You can use [destructuring](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) to assign multiple local variables, or use a property accessor like `for (x.y of iterable)` to assign the value to an object property.
However, a special rule forbids using `async` as the variable name. This is invalid syntax:
```js-nolint example-bad
let async;
for (async of [1, 2, 3]); // SyntaxError: The left-hand side of a for-of loop may not be 'async'.
```
This is to avoid syntax ambiguity with the valid code `for (async of => {};;)`, which is a [`for`](/en-US/docs/Web/JavaScript/Reference/Statements/for) loop.
## Examples
### Iterating over an Array
```js
const iterable = [10, 20, 30];
for (const value of iterable) {
console.log(value);
}
// 10
// 20
// 30
```
### Iterating over a string
Strings are [iterated by Unicode code points](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/@@iterator).
```js
const iterable = "boo";
for (const value of iterable) {
console.log(value);
}
// "b"
// "o"
// "o"
```
### Iterating over a TypedArray
```js
const iterable = new Uint8Array([0x00, 0xff]);
for (const value of iterable) {
console.log(value);
}
// 0
// 255
```
### Iterating over a Map
```js
const iterable = new Map([
["a", 1],
["b", 2],
["c", 3],
]);
for (const entry of iterable) {
console.log(entry);
}
// ['a', 1]
// ['b', 2]
// ['c', 3]
for (const [key, value] of iterable) {
console.log(value);
}
// 1
// 2
// 3
```
### Iterating over a Set
```js
const iterable = new Set([1, 1, 2, 2, 3, 3]);
for (const value of iterable) {
console.log(value);
}
// 1
// 2
// 3
```
### Iterating over the arguments object
You can iterate over the {{jsxref("Functions/arguments", "arguments")}} object to examine all parameters passed into a function.
```js
function foo() {
for (const value of arguments) {
console.log(value);
}
}
foo(1, 2, 3);
// 1
// 2
// 3
```
### Iterating over a NodeList
The following example adds a `read` class to paragraphs that are direct descendants of the [`<article>`](/en-US/docs/Web/HTML/Element/article) element by iterating over a [`NodeList`](/en-US/docs/Web/API/NodeList) DOM collection.
```js
const articleParagraphs = document.querySelectorAll("article > p");
for (const paragraph of articleParagraphs) {
paragraph.classList.add("read");
}
```
### Iterating over a user-defined iterable
Iterating over an object with an `@@iterator` method that returns a custom iterator:
```js
const iterable = {
[Symbol.iterator]() {
let i = 1;
return {
next() {
if (i <= 3) {
return { value: i++, done: false };
}
return { value: undefined, done: true };
},
};
},
};
for (const value of iterable) {
console.log(value);
}
// 1
// 2
// 3
```
Iterating over an object with an `@@iterator` generator method:
```js
const iterable = {
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
},
};
for (const value of iterable) {
console.log(value);
}
// 1
// 2
// 3
```
_Iterable iterators_ (iterators with a `[@@iterator]()` method that returns `this`) are a fairly common technique to make iterators usable in syntaxes expecting iterables, such as `for...of`.
```js
let i = 1;
const iterator = {
next() {
if (i <= 3) {
return { value: i++, done: false };
}
return { value: undefined, done: true };
},
[Symbol.iterator]() {
return this;
},
};
for (const value of iterator) {
console.log(value);
}
// 1
// 2
// 3
```
### Iterating over a generator
```js
function* source() {
yield 1;
yield 2;
yield 3;
}
const generator = source();
for (const value of generator) {
console.log(value);
}
// 1
// 2
// 3
```
### Early exiting
Execution of the `break` statement in the first loop causes it to exit early. The iterator is not finished yet, so the second loop will continue from where the first one stopped at.
```js
const source = [1, 2, 3];
const iterator = source[Symbol.iterator]();
for (const value of iterator) {
console.log(value);
if (value === 1) {
break;
}
console.log("This string will not be logged.");
}
// 1
// Another loop using the same iterator
// picks up where the last loop left off.
for (const value of iterator) {
console.log(value);
}
// 2
// 3
// The iterator is used up.
// This loop will execute no iterations.
for (const value of iterator) {
console.log(value);
}
// [No output]
```
Generators implement the [`return()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator/return) method, which causes the generator function to early return when the loop exits. This makes generators not reusable between loops.
```js example-bad
function* source() {
yield 1;
yield 2;
yield 3;
}
const generator = source();
for (const value of generator) {
console.log(value);
if (value === 1) {
break;
}
console.log("This string will not be logged.");
}
// 1
// The generator is used up.
// This loop will execute no iterations.
for (const value of generator) {
console.log(value);
}
// [No output]
```
### Difference between for...of and for...in
Both `for...in` and `for...of` statements iterate over something. The main difference between them is in what they iterate over.
The {{jsxref("Statements/for...in", "for...in")}} statement iterates over the [enumerable string properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) of an object, while the `for...of` statement iterates over values that the [iterable object](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) defines to be iterated over.
The following example shows the difference between a `for...of` loop and a `for...in` loop when used with an {{jsxref("Array")}}.
```js
Object.prototype.objCustom = function () {};
Array.prototype.arrCustom = function () {};
const iterable = [3, 5, 7];
iterable.foo = "hello";
for (const i in iterable) {
console.log(i);
}
// "0", "1", "2", "foo", "arrCustom", "objCustom"
for (const i in iterable) {
if (Object.hasOwn(iterable, i)) {
console.log(i);
}
}
// "0" "1" "2" "foo"
for (const i of iterable) {
console.log(i);
}
// 3 5 7
```
The object `iterable` inherits the properties `objCustom` and `arrCustom` because it contains both `Object.prototype` and `Array.prototype` in its [prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain).
The `for...in` loop logs only [enumerable properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) of the `iterable` object. It doesn't log array _elements_ `3`, `5`, `7` or `"hello"` because those are not _properties_ β they are _values_. It logs array _indexes_ as well as `arrCustom` and `objCustom`, which are actual properties. If you're not sure why these properties are iterated over, there's a more thorough explanation of how [array iteration and `for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in#array_iteration_and_for...in) work.
The second loop is similar to the first one, but it uses {{jsxref("Object.hasOwn()")}} to check if the found enumerable property is the object's own, i.e. not inherited. If it is, the property is logged. Properties `0`, `1`, `2` and `foo` are logged because they are own properties. Properties `arrCustom` and `objCustom` are not logged because they are inherited.
The `for...of` loop iterates and logs _values_ that `iterable`, as an array (which is [iterable](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@iterator)), defines to be iterated over. The object's _elements_ `3`, `5`, `7` are shown, but none of the object's _properties_ are.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Array.prototype.forEach()")}}
- {{jsxref("Map.prototype.forEach()")}}
- {{jsxref("Object.entries()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/const/index.md | ---
title: const
slug: Web/JavaScript/Reference/Statements/const
page-type: javascript-statement
browser-compat: javascript.statements.const
---
{{jsSidebar("Statements")}}
The **`const`** declaration declares block-scoped local variables. The value of a constant can't be changed through reassignment using the [assignment operator](/en-US/docs/Web/JavaScript/Reference/Operators/Assignment), but if a constant is an [object](/en-US/docs/Web/JavaScript/Data_structures#objects), its properties can be added, updated, or removed.
{{EmbedInteractiveExample("pages/js/statement-const.html")}}
## Syntax
```js-nolint
const name1 = value1;
const name1 = value1, name2 = value2;
const name1 = value1, name2 = value2, /* β¦, */ nameN = valueN;
```
- `nameN`
- : The name of the variable to declare. Each must be a legal JavaScript [identifier](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers) or a [destructuring binding pattern](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment).
- `valueN`
- : Initial value of the variable. It can be any legal expression.
## Description
The `const` declaration is very similar to {{jsxref("Statements/let", "let")}}:
- `const` declarations are scoped to blocks as well as functions.
- `const` declarations can only be accessed after the place of declaration is reached (see [temporal dead zone](/en-US/docs/Web/JavaScript/Reference/Statements/let#temporal_dead_zone_tdz)). For this reason, `const` declarations are commonly regarded as [non-hoisted](/en-US/docs/Glossary/Hoisting).
- `const` declarations do not create properties on {{jsxref("globalThis")}} when declared at the top level of a script.
- `const` declarations cannot be [redeclared](/en-US/docs/Web/JavaScript/Reference/Statements/let#redeclarations) by any other declaration in the same scope.
- `const` begins [_declarations_, not _statements_](/en-US/docs/Web/JavaScript/Reference/Statements#difference_between_statements_and_declarations). That means you cannot use a lone `const` declaration as the body of a block (which makes sense, since there's no way to access the variable).
```js-nolint example-bad
if (true) const a = 1; // SyntaxError: Lexical declaration cannot appear in a single-statement context
```
An initializer for a constant is required. You must specify its value in the same declaration. (This makes sense, given that it can't be changed later.)
```js-nolint example-bad
const FOO; // SyntaxError: Missing initializer in const declaration
```
The `const` declaration creates an immutable reference to a value. It does _not_ mean the value it holds is immutable β just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered. You should understand `const` declarations as "create a variable whose _identity_ remains constant", not "whose _value_ remains constant" β or, "create immutable {{Glossary("binding", "bindings")}}", not "immutable values".
Many style guides (including [MDN's](/en-US/docs/MDN/Writing_guidelines/Writing_style_guide/Code_style_guide/JavaScript#variable_declarations)) recommend using `const` over {{jsxref("Statements/let", "let")}} whenever a variable is not reassigned in its scope. This makes the intent clear that a variable's type (or value, in the case of a primitive) can never change. Others may prefer `let` for non-primitives that are mutated.
The list that follows the `const` keyword is called a _{{Glossary("binding")}} list_ and is separated by commas, where the commas are _not_ [comma operators](/en-US/docs/Web/JavaScript/Reference/Operators/Comma_operator) and the `=` signs are _not_ [assignment operators](/en-US/docs/Web/JavaScript/Reference/Operators/Assignment). Initializers of later variables can refer to earlier variables in the list.
## Examples
### Basic const usage
Constants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters, especially for primitives because they are truly immutable.
```js
// define MY_FAV as a constant and give it the value 7
const MY_FAV = 7;
console.log("my favorite number is: " + MY_FAV);
```
```js-nolint example-bad
// Re-assigning to a constant variable throws an error
MY_FAV = 20; // TypeError: Assignment to constant variable
// Redeclaring a constant throws an error
const MY_FAV = 20; // SyntaxError: Identifier 'MY_FAV' has already been declared
var MY_FAV = 20; // SyntaxError: Identifier 'MY_FAV' has already been declared
let MY_FAV = 20; // SyntaxError: Identifier 'MY_FAV' has already been declared
```
### Block scoping
It's important to note the nature of block scoping.
```js-nolint
const MY_FAV = 7;
if (MY_FAV === 7) {
// This is fine because it's in a new block scope
const MY_FAV = 20;
console.log(MY_FAV); // 20
// var declarations are not scoped to blocks so this throws an error
var MY_FAV = 20; // SyntaxError: Identifier 'MY_FAV' has already been declared
}
console.log(MY_FAV); // 7
```
### const in objects and arrays
`const` also works on objects and arrays. Attempting to overwrite the object throws an error "Assignment to constant variable".
```js example-bad
const MY_OBJECT = { key: "value" };
MY_OBJECT = { OTHER_KEY: "value" };
```
However, object keys are not protected, so the following statement is executed without problem.
```js
MY_OBJECT.key = "otherValue";
```
You would need to use {{jsxref("Object.freeze()")}} to make an object immutable.
The same applies to arrays. Assigning a new array to the variable throws an error "Assignment to constant variable".
```js example-bad
const MY_ARRAY = [];
MY_ARRAY = ["B"];
```
Still, it's possible to push items into the array and thus mutate it.
```js
MY_ARRAY.push("A"); // ["A"]
```
### Declaration with destructuring
The left-hand side of each `=` can also be a binding pattern. This allows creating multiple variables at once.
```js
const result = /(a+)(b+)(c+)/.exec("aaabcc");
const [, a, b, c] = result;
console.log(a, b, c); // "aaa" "b" "cc"
```
For more information, see [Destructuring assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Statements/var", "var")}}
- {{jsxref("Statements/let", "let")}}
- [Constants in the JavaScript Guide](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#constants)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/while/index.md | ---
title: while
slug: Web/JavaScript/Reference/Statements/while
page-type: javascript-statement
browser-compat: javascript.statements.while
---
{{jsSidebar("Statements")}}
The **`while`** statement creates a loop that executes a specified statement
as long as the test condition evaluates to true. The condition is evaluated before
executing the statement.
{{EmbedInteractiveExample("pages/js/statement-while.html")}}
## Syntax
```js-nolint
while (condition)
statement
```
- `condition`
- : An expression evaluated before each pass through the loop. If this condition
[evaluates to true](/en-US/docs/Glossary/Truthy), `statement` is executed. When condition
[evaluates to false](/en-US/docs/Glossary/Falsy), execution continues with the statement after the
`while` loop.
- `statement`
- : An optional statement that is executed as long as the condition evaluates to true.
To execute multiple statements within the loop, use a {{jsxref("Statements/block", "block", "", 1)}} statement
(`{ /* ... */ }`) to group those statements.
Note: Use the {{jsxref("Statements/break", "break")}} statement to stop a loop before `condition` evaluates
to true.
## Examples
### Using while
The following `while` loop iterates as long as `n` is less than
three.
```js
let n = 0;
let x = 0;
while (n < 3) {
n++;
x += n;
}
```
Each iteration, the loop increments `n` and adds it to `x`.
Therefore, `x` and `n` take on the following values:
- After the first pass: `n` = 1 and `x` = 1
- After the second pass: `n` = 2 and `x` = 3
- After the third pass: `n` = 3 and `x` = 6
After completing the third pass, the condition `n` < 3 is no longer true,
so the loop terminates.
### Using an assignment as a condition
In some cases, it can make sense to use an assignment as a condition. This comes with readability tradeoffs, so there are certain stylistic recommendations that would make the pattern more obvious for everyone.
Consider the following example, which iterates over a document's comments, logging them to the console.
```js-nolint example-bad
const iterator = document.createNodeIterator(document, NodeFilter.SHOW_COMMENT);
let currentNode;
while (currentNode = iterator.nextNode()) {
console.log(currentNode.textContent.trim());
}
```
That's not completely a good-practice example, due to the following line specifically:
```js-nolint example-bad
while (currentNode = iterator.nextNode()) {
```
The _effect_ of that line is fine β in that, each time a comment node is found:
1. `iterator.nextNode()` returns that comment node, which gets assigned to `currentNode`.
2. The value of `currentNode = iterator.nextNode()` is therefore [truthy](/en-US/docs/Glossary/Truthy).
3. So the `console.log()` call executes and the loop continues.
β¦and then, when there are no more comment nodes in the document:
1. `iterator.nextNode()` returns [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null).
2. The value of `currentNode = iterator.nextNode()` is therefore also `null`, which is [falsy](/en-US/docs/Glossary/Falsy).
3. So the loop ends.
The problem with this line is: conditions typically use [comparison operators](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#comparison_operators) such as `===`, but the `=` in that line isn't a comparison operator β instead, it's an [assignment operator](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#assignment_operators). So that `=` _looks like_ it's a typo for `===` β even though it's _not_ actually a typo.
Therefore, in cases like that one, some [code-linting tools](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Introducing_complete_toolchain#code_linting_tools) such as ESLint's [`no-cond-assign`](https://eslint.org/docs/latest/rules/no-cond-assign) rule β in order to help you catch a possible typo so that you can fix it β will report a warning such as the following:
> Expected a conditional expression and instead saw an assignment.
Many style guides recommend more explicitly indicating the intention for the condition to be an assignment. You can do that minimally by putting additional parentheses as a [grouping operator](/en-US/docs/Web/JavaScript/Reference/Operators/Grouping) around the assignment:
```js example-good
const iterator = document.createNodeIterator(document, NodeFilter.SHOW_COMMENT);
let currentNode;
while ((currentNode = iterator.nextNode())) {
console.log(currentNode.textContent.trim());
}
```
In fact, this is the style enforced by ESLint's `no-cond-assign`'s default configuration, as well as [Prettier](https://prettier.io/), so you'll likely see this pattern a lot in the wild.
Some people may further recommend adding a comparison operator to turn the condition into an explicit comparison:
```js-nolint example-good
while ((currentNode = iterator.nextNode()) !== null) {
```
There are other ways to write this pattern, such as:
```js-nolint example-good
while ((currentNode = iterator.nextNode()) && currentNode) {
```
Or, forgoing the idea of using a `while` loop altogether:
```js example-good
const iterator = document.createNodeIterator(document, NodeFilter.SHOW_COMMENT);
for (
let currentNode = iterator.nextNode();
currentNode;
currentNode = iterator.nextNode()
) {
console.log(currentNode.textContent.trim());
}
```
If the reader is sufficiently familiar with the assignment as condition pattern, all these variations should have equivalent readability. Otherwise, the last form is probably the most readable, albeit the most verbose.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Statements/do...while", "do...while")}}
- {{jsxref("Statements/for", "for")}}
- {{jsxref("Statements/break", "break")}}
- {{jsxref("Statements/continue", "continue")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/function_star_/index.md | ---
title: function*
slug: Web/JavaScript/Reference/Statements/function*
page-type: javascript-statement
browser-compat: javascript.statements.generator_function
---
{{jsSidebar("Statements")}}
The **`function*`** declaration creates a {{Glossary("binding")}} of a new generator function to a given name. A generator function can be exited and later re-entered, with its context (variable {{Glossary("binding", "bindings")}}) saved across re-entrances.
You can also define generator functions using the [`function*` expression](/en-US/docs/Web/JavaScript/Reference/Operators/function*).
{{EmbedInteractiveExample("pages/js/statement-functionasterisk.html")}}
## Syntax
```js-nolint
function* name(param0) {
statements
}
function* name(param0, param1) {
statements
}
function* name(param0, param1, /* β¦, */ paramN) {
statements
}
```
> **Note:** Generator functions do not have arrow function counterparts.
> **Note:** `function` and `*` are separate tokens, so they can be separated by [whitespace or line terminators](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#white_space).
### Parameters
- `name`
- : The function name.
- `param` {{optional_inline}}
- : The name of a formal parameter for the function. For the parameters' syntax, see the [Functions reference](/en-US/docs/Web/JavaScript/Guide/Functions#function_parameters).
- `statements` {{optional_inline}}
- : The statements comprising the body of the function.
## Description
A `function*` declaration creates a {{jsxref("GeneratorFunction")}} object. Each time when a generator function is called, it returns a new {{jsxref("Generator")}} object, which conforms to the [iterator protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol). When the iterator's `next()`
method is called, the generator function's body is executed until the first
{{jsxref("Operators/yield", "yield")}} expression, which specifies the value to be
returned from the iterator or, with {{jsxref("Operators/yield*", "yield*")}}, delegates
to another generator function. The `next()` method returns an object with a
`value` property containing the yielded value and a `done`
property which indicates whether the generator has yielded its last value, as a boolean.
Calling the `next()` method with an argument will resume the generator
function execution, replacing the `yield` expression where an execution was
paused with the argument from `next()`.
Generators in JavaScript β especially when combined with Promises β are a very
powerful tool for asynchronous programming as they mitigate β if not entirely eliminate
\-- the problems with callbacks, such as [Callback Hell](http://callbackhell.com/) and
[Inversion of Control](https://frontendmasters.com/courses/rethinking-async-js/callback-problems-inversion-of-control/).
However, an even simpler solution to these problems can be achieved
with {{jsxref("Statements/async_function", "async functions", "", 1)}}.
A `return` statement in a generator, when executed, will make the generator
finish (i.e. the `done` property of the object returned by it will be set to
`true`). If a value is returned, it will be set as the `value`
property of the object returned by the generator.
Much like a `return` statement, an error thrown inside the generator will
make the generator finished β unless caught within the generator's body.
When a generator is finished, subsequent `next()` calls will not execute any
of that generator's code, they will just return an object of this form:
`{value: undefined, done: true}`.
`function*` declarations behave similar to {{jsxref("Statements/function", "function")}} declarations β they are [hoisted](/en-US/docs/Glossary/Hoisting) to the top of their scope and can be called anywhere in their scope, and they can be redeclared only in certain contexts.
## Examples
### Simple example
```js
function* idMaker() {
let index = 0;
while (true) {
yield index++;
}
}
const gen = idMaker();
console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3
// β¦
```
### Example with yield\*
```js
function* anotherGenerator(i) {
yield i + 1;
yield i + 2;
yield i + 3;
}
function* generator(i) {
yield i;
yield* anotherGenerator(i);
yield i + 10;
}
const gen = generator(10);
console.log(gen.next().value); // 10
console.log(gen.next().value); // 11
console.log(gen.next().value); // 12
console.log(gen.next().value); // 13
console.log(gen.next().value); // 20
```
### Passing arguments into Generators
```js
function* logGenerator() {
console.log(0);
console.log(1, yield);
console.log(2, yield);
console.log(3, yield);
}
const gen = logGenerator();
// the first call of next executes from the start of the function
// until the first yield statement
gen.next(); // 0
gen.next("pretzel"); // 1 pretzel
gen.next("california"); // 2 california
gen.next("mayonnaise"); // 3 mayonnaise
```
### Return statement in a generator
```js
function* yieldAndReturn() {
yield "Y";
return "R";
yield "unreachable";
}
const gen = yieldAndReturn();
console.log(gen.next()); // { value: "Y", done: false }
console.log(gen.next()); // { value: "R", done: true }
console.log(gen.next()); // { value: undefined, done: true }
```
### Generator as an object property
```js
const someObj = {
*generator() {
yield "a";
yield "b";
},
};
const gen = someObj.generator();
console.log(gen.next()); // { value: 'a', done: false }
console.log(gen.next()); // { value: 'b', done: false }
console.log(gen.next()); // { value: undefined, done: true }
```
### Generator as an object method
```js
class Foo {
*generator() {
yield 1;
yield 2;
yield 3;
}
}
const f = new Foo();
const gen = f.generator();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: undefined, done: true }
```
### Generator as a computed property
```js
class Foo {
*[Symbol.iterator]() {
yield 1;
yield 2;
}
}
const SomeObj = {
*[Symbol.iterator]() {
yield "a";
yield "b";
},
};
console.log(Array.from(new Foo())); // [ 1, 2 ]
console.log(Array.from(SomeObj)); // [ 'a', 'b' ]
```
### Generators are not constructable
```js
function* f() {}
const obj = new f(); // throws "TypeError: f is not a constructor
```
### Generator defined in an expression
```js
const foo = function* () {
yield 10;
yield 20;
};
const bar = foo();
console.log(bar.next()); // {value: 10, done: false}
```
### Generator example
```js
function* powers(n) {
//endless loop to generate
for (let current = n; ; current *= n) {
yield current;
}
}
for (const power of powers(2)) {
// controlling generator
if (power > 32) {
break;
}
console.log(power);
// 2
// 4
// 8
// 16
// 32
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Functions](/en-US/docs/Web/JavaScript/Guide/Functions) guide
- [Iterators and generators](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators) guide
- [Functions](/en-US/docs/Web/JavaScript/Reference/Functions)
- {{jsxref("GeneratorFunction")}}
- [`function*` expression](/en-US/docs/Web/JavaScript/Reference/Operators/function*)
- {{jsxref("Statements/function", "function")}}
- {{jsxref("Statements/async_function", "async function")}}
- {{jsxref("Statements/async_function*", "async function*")}}
- [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
- {{jsxref("Operators/yield", "yield")}}
- {{jsxref("Operators/yield*", "yield*")}}
- {{jsxref("Generator")}}
- [Regenerator](https://github.com/facebook/regenerator) on GitHub
- [Promises and Generators: control flow utopia](https://youtu.be/qbKWsbJ76-s) presentation by Forbes Lindesay at JSConf (2013)
- [Task.js](https://github.com/mozilla/task.js) on GitHub
- [You Don't Know JS: Async & Performance, Ch.4: Generators](https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/async%20%26%20performance/ch4.md) by Kyle Simpson
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/for/index.md | ---
title: for
slug: Web/JavaScript/Reference/Statements/for
page-type: javascript-statement
browser-compat: javascript.statements.for
---
{{jsSidebar("Statements")}}
The **`for`** statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a [block statement](/en-US/docs/Web/JavaScript/Reference/Statements/block)) to be executed in the loop.
{{EmbedInteractiveExample("pages/js/statement-for.html")}}
## Syntax
```js-nolint
for (initialization; condition; afterthought)
statement
```
- `initialization` {{optional_inline}}
- : An expression (including [assignment expressions](/en-US/docs/Web/JavaScript/Reference/Operators/Assignment)) or variable declaration evaluated once before the loop begins. Typically used to initialize a counter variable. This expression may optionally declare new variables with `var` or `let` keywords. Variables declared with `var` are not local to the loop, i.e. they are in the same scope the `for` loop is in. Variables declared with `let` are local to the statement.
The result of this expression is discarded.
- `condition` {{optional_inline}}
- : An expression to be evaluated before each loop iteration. If this expression [evaluates to true](/en-US/docs/Glossary/Truthy), `statement` is executed. If the expression [evaluates to false](/en-US/docs/Glossary/Falsy), execution exits the loop and goes to the first statement after the `for` construct.
This conditional test is optional. If omitted, the condition always evaluates to true.
- `afterthought` {{optional_inline}}
- : An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of `condition`. Generally used to update or increment the counter variable.
- `statement`
- : A statement that is executed as long as the condition evaluates to true. You can use a [block statement](/en-US/docs/Web/JavaScript/Reference/Statements/block) to execute multiple statements. To execute no statement within the loop, use an [empty statement](/en-US/docs/Web/JavaScript/Reference/Statements/Empty) (`;`).
## Examples
### Using for
The following `for` statement starts by declaring the variable `i` and initializing it to `0`. It checks that `i` is less than nine, performs the two succeeding statements, and increments `i` by 1 after each pass through the loop.
```js
for (let i = 0; i < 9; i++) {
console.log(i);
// more statements
}
```
### Initialization block syntax
The initialization block accepts both expressions and variable declarations. However, expressions cannot use the [`in`](/en-US/docs/Web/JavaScript/Reference/Operators/in) operator unparenthesized, because that is ambiguous with a [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in) loop.
```js-nolint example-bad
for (let i = "start" in window ? window.start : 0; i < 9; i++) {
console.log(i);
}
// SyntaxError: 'for-in' loop variable declaration may not have an initializer.
```
```js-nolint example-good
// Parenthesize the whole initializer
for (let i = ("start" in window ? window.start : 0); i < 9; i++) {
console.log(i);
}
// Parenthesize the `in` expression
for (let i = ("start" in window) ? window.start : 0; i < 9; i++) {
console.log(i);
}
```
### Optional for expressions
All three expressions in the head of the `for` loop are optional. For example, it is not required to use the `initialization` block to initialize variables:
```js
let i = 0;
for (; i < 9; i++) {
console.log(i);
// more statements
}
```
Like the `initialization` block, the `condition` part is also optional. If you are omitting this expression, you must make sure to break the loop in the body in order to not create an infinite loop.
```js
for (let i = 0; ; i++) {
console.log(i);
if (i > 3) break;
// more statements
}
```
You can also omit all three expressions. Again, make sure to use a {{jsxref("Statements/break", "break")}} statement to end the loop and also modify (increase) a variable, so that the condition for the break statement is true at some point.
```js
let i = 0;
for (;;) {
if (i > 3) break;
console.log(i);
i++;
}
```
However, in the case where you are not fully using all three expression positions β especially if you are not declaring variables with the first expression but mutating something in the upper scope β consider using a [`while`](/en-US/docs/Web/JavaScript/Reference/Statements/while) loop instead, which makes the intention clearer.
```js
let i = 0;
while (i <= 3) {
console.log(i);
i++;
}
```
### Lexical declarations in the initialization block
Declaring a variable within the initialization block has important differences from declaring it in the upper [scope](/en-US/docs/Glossary/Scope), especially when creating a [closure](/en-US/docs/Web/JavaScript/Closures) within the loop body. For example, for the code below:
```js
for (let i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, 1000);
}
```
It logs `0`, `1`, and `2`, as expected. However, if the variable is defined in the upper scope:
```js
let i = 0;
for (; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, 1000);
}
```
It logs `3`, `3`, and `3`. The reason is that each `setTimeout` creates a new closure that closes over the `i` variable, but if the `i` is not scoped to the loop body, all closures will reference the same variable when they eventually get called β and due to the asynchronous nature of [`setTimeout`](/en-US/docs/Web/API/setTimeout), it will happen after the loop has already exited, causing the value of `i` in all queued callbacks' bodies to have the value of `3`.
This also happens if you use a `var` statement as the initialization, because variables declared with `var` are only function-scoped, but not lexically scoped (i.e. they can't be scoped to the loop body).
```js
for (var i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, 1000);
}
// Logs 3, 3, 3
```
The scoping effect of the initialization block can be understood as if the declaration happens within the loop body, but just happens to be accessible within the `condition` and `afterthought` parts. More precisely, `let` declarations are special-cased by `for` loops β if `initialization` is a `let` declaration, then every time, after the loop body is evaluated, the following happens:
1. A new lexical scope is created with new `let`-declared variables.
2. The binding values from the last iteration are used to re-initialize the new variables.
3. `afterthought` is evaluated in the new scope.
So re-assigning the new variables within `afterthought` does not affect the bindings from the previous iteration.
A new lexical scope is also created after `initialization`, just before `condition` is evaluated for the first time. These details can be observed by creating closures, which allow to get hold of a binding at any particular point. For example, in this code a closure created within the `initialization` section does not get updated by re-assignments of `i` in the `afterthought`:
```js
for (let i = 0, getI = () => i; i < 3; i++) {
console.log(getI());
}
// Logs 0, 0, 0
```
This does not log "0, 1, 2", like what would happen if `getI` is declared in the loop body. This is because `getI` is not re-evaluated on each iteration β rather, the function is created once and closes over the `i` variable, which refers to the variable declared when the loop was first initialized. Subsequent updates to the value of `i` actually create new variables called `i`, which `getI` does not see. A way to fix this is to re-compute `getI` every time `i` updates:
```js
for (let i = 0, getI = () => i; i < 3; i++, getI = () => i) {
console.log(getI());
}
// Logs 0, 1, 2
```
The `i` variable inside the `initialization` is distinct from the `i` variable inside every iteration, including the first. So, in this example, `getI` returns 0, even though the value of `i` inside the iteration is incremented beforehand:
```js
for (let i = 0, getI = () => i; i < 3; ) {
i++;
console.log(getI());
}
// Logs 0, 0, 0
```
In fact, you can capture this initial binding of the `i` variable and re-assign it later, and this updated value will not be visible to the loop body, which sees the next new binding of `i`.
```js
for (
let i = 0, getI = () => i, incrementI = () => i++;
getI() < 3;
incrementI()
) {
console.log(i);
}
// Logs 0, 0, 0
```
This logs "0, 0, 0", because the `i` variable in each loop evaluation is actually a separate variable, but `getI` and `incrementI` both read and write the _initial_ binding of `i`, not what was subsequently declared.
### Using for without a body
The following `for` cycle calculates the offset position of a node in the `afterthought` section, and therefore it does not require the use of a `statement` section, a semicolon is used instead.
```js
function showOffsetPos(id) {
let left = 0;
let top = 0;
for (
let itNode = document.getElementById(id); // initialization
itNode; // condition
left += itNode.offsetLeft,
top += itNode.offsetTop,
itNode = itNode.offsetParent // afterthought
); // semicolon
console.log(
`Offset position of "${id}" element:
left: ${left}px;
top: ${top}px;`,
);
}
showOffsetPos("content");
// Logs:
// Offset position of "content" element:
// left: 0px;
// top: 153px;
```
Note that the semicolon after the `for` statement is mandatory, because it stands as an [empty statement](/en-US/docs/Web/JavaScript/Reference/Statements/Empty). Otherwise, the `for` statement acquires the following `console.log` line as its `statement` section, which makes the `log` execute multiple times.
### Using for with two iterating variables
You can create two counters that are updated simultaneously in a for loop using the [comma operator](/en-US/docs/Web/JavaScript/Reference/Operators/Comma_operator). Multiple `let` and `var` declarations can also be joined with commas.
```js
const arr = [1, 2, 3, 4, 5, 6];
for (let l = 0, r = arr.length - 1; l < r; l++, r--) {
console.log(arr[l], arr[r]);
}
// 1 6
// 2 5
// 3 4
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Empty statement](/en-US/docs/Web/JavaScript/Reference/Statements/Empty)
- {{jsxref("Statements/break", "break")}}
- {{jsxref("Statements/continue", "continue")}}
- {{jsxref("Statements/while", "while")}}
- {{jsxref("Statements/do...while", "do...while")}}
- {{jsxref("Statements/for...in", "for...in")}}
- {{jsxref("Statements/for...of", "for...of")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/with/index.md | ---
title: with
slug: Web/JavaScript/Reference/Statements/with
page-type: javascript-statement
status:
- deprecated
browser-compat: javascript.statements.with
---
{{jsSidebar("Statements")}}{{Deprecated_Header}}
> **Note:** Use of the `with` statement is not recommended, as it may be the source of confusing bugs and compatibility issues, makes optimization impossible, and is forbidden in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode). The recommended alternative is to assign the object whose properties you want to access to a temporary variable.
The **`with`** statement extends the scope chain for a statement.
## Syntax
```js-nolint
with (expression)
statement
```
- `expression`
- : Adds the given expression to the scope chain used when evaluating the statement. The parentheses around the expression are required.
- `statement`
- : Any statement. To execute multiple statements, use a [block](/en-US/docs/Web/JavaScript/Reference/Statements/block) statement (`{ ... }`) to group those statements.
## Description
There are two types of identifiers: a _qualified_ identifier and an _unqualified_ identifier. An unqualified identifier is one that does not indicate where it comes from.
```js
foo; // unqualified identifier
foo.bar; // bar is a qualified identifier
```
Normally, an unqualified identifier is resolved by searching the scope chain for a variable with that name, while a qualified identifier is resolved by searching the prototype chain of an object for a property with that name.
```js
const foo = { bar: 1 };
console.log(foo.bar);
// foo is found in the scope chain as a variable;
// bar is found in foo as a property
```
One exception to this is the [global object](/en-US/docs/Glossary/Global_object), which sits on top of the scope chain, and whose properties automatically become global variables that can be referred to without qualifiers.
```js
console.log(globalThis.Math === Math); // true
```
The `with` statement adds the given object to the head of this scope chain during the evaluation of its statement body. Every unqualified name would first be searched within the object (through a [`in`](/en-US/docs/Web/JavaScript/Reference/Operators/in) check) before searching in the upper scope chain.
Note that if the unqualified reference refers to a method of the object, the method is called with the object as its `this` value.
```js
with ([1, 2, 3]) {
console.log(toString()); // 1,2,3
}
```
The object may have an [`@@unscopables`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/unscopables) property, which defines a list of properties that should not be added to the scope chain (for backward compatibility). See the [`Symbol.unscopables`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/unscopables) documentation for more information.
The reasons to use a `with` statement include saving one temporary variable and reducing file size by avoiding repeating a lengthy object reference. However, there are far more reasons why `with` statements are not desirable:
- Performance: The `with` statement forces the specified object to be searched first for all name lookups. Therefore, all identifiers that aren't members of the specified object will be found more slowly in a `with` block. Moreover, the optimizer cannot make any assumptions about what each unqualified identifier refers to, so it must repeat the same property lookup every time the identifier is used.
- Readability: The `with` statement makes it hard for a human reader or JavaScript compiler to decide whether an unqualified name will be found along the scope chain, and if so, in which object. For example:
```js
function f(x, o) {
with (o) {
console.log(x);
}
}
```
If you look just at the definition of `f`, it's impossible to tell what the `x` in the `with` body refers to. Only when `f` is called can `x` be determined to be `o.x` or `f`'s first formal parameter. If you forget to define `x` in the object you pass as the second parameter, you won't get an error β instead you'll just get unexpected results. It's also unclear what the actual intent of such code would be.
- Forward compatibility: Code using `with` may not be forward compatible, especially when used with something other than a plain object, which may gain more properties in the future. Consider this example:
```js
function f(foo, values) {
with (foo) {
console.log(values);
}
}
```
If you call `f([1, 2, 3], obj)` in an ECMAScript 5 environment, the `values` reference inside the `with` statement will resolve to `obj`. However, ECMAScript 2015 introduces a [`values`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/values) property on `Array.prototype` (so it will be available on every array). So, after upgrading the environment, the `values` reference inside the `with` statement resolves to `[1, 2, 3].values` instead, and is likely to cause bugs.
In this particular example, `values` is defined as unscopable through [`Array.prototype[@@unscopables]`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@unscopables), so it still correctly resolves to the `values` parameter. If it were not defined as unscopable, one can see how this would be a difficult issue to debug.
## Examples
### Using the with statement
The following `with` statement specifies that the {{jsxref("Math")}} object is the default object. The statements following the `with` statement refer to the {{jsxref("Math/PI", "PI")}} property and the {{jsxref("Math/cos", "cos")}} and {{jsxref("Math/sin", "sin")}} methods, without specifying an object. JavaScript assumes the `Math` object for these references.
```js
let a, x, y;
const r = 10;
with (Math) {
a = PI * r * r;
x = r * cos(PI);
y = r * sin(PI / 2);
}
```
### Avoiding the with statement by destructuring properties into the current scope
You can usually avoid using `with` through [property destructuring](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment). Here we create an extra block to mimic the behavior of `with` creating an extra scope β but in actual usage, this block can usually be omitted.
```js
let a, x, y;
const r = 10;
{
const { PI, cos, sin } = Math;
a = PI * r * r;
x = r * cos(PI);
y = r * sin(PI / 2);
}
```
### Avoiding the with statement by using an IIFE
If you're producing an expression that must reuse a long-named reference multiple times, and your goal is to eliminate that lengthy name within your expression, you can wrap the expression in an [IIFE](/en-US/docs/Glossary/IIFE) and provide the long name as an argument.
```js
const objectHavingAnEspeciallyLengthyName = { foo: true, bar: false };
if (((o) => o.foo && !o.bar)(objectHavingAnEspeciallyLengthyName)) {
// This branch runs.
}
```
### Creating dynamic namespaces using the with statement and a proxy
`with` will transform every variable lookup to a property lookup, while [Proxies](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) allow trapping every property lookup call. You can create a dynamic namespace by combining them.
```js
const namespace = new Proxy(
{},
{
has(target, key) {
// Avoid trapping global properties like `console`
if (key in globalThis) {
return false;
}
// Trap all property lookups
return true;
},
get(target, key) {
return key;
},
},
);
with (namespace) {
console.log(a, b, c); // "a" "b" "c"
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Statements/block", "block", "", 1)}}
- [Strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode)
- {{jsxref("Symbol.unscopables")}}
- {{jsxref("Array/@@unscopables", "Array.prototype[@@unscopables]")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/break/index.md | ---
title: break
slug: Web/JavaScript/Reference/Statements/break
page-type: javascript-statement
browser-compat: javascript.statements.break
---
{{jsSidebar("Statements")}}
The **`break`** statement terminates the current loop or {{jsxref("Statements/switch", "switch")}} statement and transfers program control to the statement following the terminated statement. It can also be used to jump past a [labeled statement](/en-US/docs/Web/JavaScript/Reference/Statements/label) when used within that labeled statement.
{{EmbedInteractiveExample("pages/js/statement-break.html")}}
## Syntax
```js-nolint
break;
break label;
```
- `label` {{optional_inline}}
- : Identifier associated with the label of the statement to break to. If the `break` statement is not nested within a loop or {{jsxref("Statements/switch", "switch")}}, then the label identifier is required.
## Description
When `break;` is encountered, the program breaks out of the innermost `switch` or [looping](/en-US/docs/Web/JavaScript/Reference/Statements#iterations) statement and continues executing the next statement after that.
When `break label;` is encountered, the program breaks out of the statement labeled with `label` and continues executing the next statement after that. The `break` statement needs to be nested within the referenced label. The labeled statement can be any statement (commonly a {{jsxref("Statements/block", "block", "", 1)}} statement); it does not have to be another loop statement.
A `break` statement, with or without a following label, cannot be used at the top level of a script, module, function's body, or [static initialization block](/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks), even when the function or class is further contained within a loop.
## Examples
### break in while loop
The following function has a `break` statement that terminates the {{jsxref("Statements/while", "while")}} loop when `i` is 3, and then returns the value `3 * x`.
```js
function testBreak(x) {
let i = 0;
while (i < 6) {
if (i === 3) {
break;
}
i += 1;
}
return i * x;
}
```
### break in switch statements
The following code has a `break` statement that terminates the {{jsxref("Statements/switch", "switch")}} statement when a case is matched and the corresponding code has run.
```js
const food = "sushi";
switch (food) {
case "sushi":
console.log("Sushi is originally from Japan.");
break;
case "pizza":
console.log("Pizza is originally from Italy.");
break;
default:
console.log("I have never heard of that dish.");
break;
}
```
### break in labeled blocks
The following code uses `break` statements with labeled blocks. By using `break outerBlock`, control is transferred to the end of the block statement marked as `outerBlock`.
```js
outerBlock: {
innerBlock: {
console.log("1");
break outerBlock; // breaks out of both innerBlock and outerBlock
console.log(":-("); // skipped
}
console.log("2"); // skipped
}
```
### Unsyntactic break statements
A `break` statement must be nested within any label it references. The following code also uses `break` statements with labeled blocks, but generates a syntax error because its `break` statement references `block2` but it's not nested within `block2`.
```js-nolint example-bad
block1: {
console.log("1");
break block2; // SyntaxError: label not found
}
block2: {
console.log("2");
}
```
Syntax errors are also generated in the following code examples which use `break` statements within functions that are nested within a loop, or labeled block that the `break` statements are intended to break out of.
```js-nolint example-bad
function testBreak(x) {
let i = 0;
while (i < 6) {
if (i === 3) {
(() => {
break;
})();
}
i += 1;
}
return i * x;
}
testBreak(1); // SyntaxError: Illegal break statement
```
```js-nolint example-bad
block1: {
console.log("1");
(() => {
break block1; // SyntaxError: Undefined label 'block1'
})();
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Statements/continue", "continue")}}
- {{jsxref("Statements/label", "label", "", 1)}}
- {{jsxref("Statements/switch", "switch")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/label/index.md | ---
title: Labeled statement
slug: Web/JavaScript/Reference/Statements/label
page-type: javascript-statement
browser-compat: javascript.statements.label
---
{{jsSidebar("Statements")}}
A **labeled statement** is any [statement](/en-US/docs/Web/JavaScript/Reference/Statements) that is prefixed with an identifier. You can jump to this label using a {{jsxref("Statements/break", "break")}} or {{jsxref("Statements/continue", "continue")}} statement nested within the labeled statement.
{{EmbedInteractiveExample("pages/js/statement-label.html")}}
## Syntax
```js-nolint
label:
statement
```
- `label`
- : Any JavaScript [identifier](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers) that is not a [reserved word](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#reserved_words).
- `statement`
- : A JavaScript statement. `break` can be used within any labeled statement, and `continue` can be used within labeled looping statements.
## Description
You can use a label to identify a statement, and later refer to it using a `break` or `continue` statement. Note that JavaScript has _no_ `goto` statement; you can only use labels with `break` or `continue`.
Any `break` or `continue` that references `label` must be contained within the `statement` that's labeled by `label`. Think about `label` as a variable that's only available in the scope of `statement`.
If a `break label;` statement is encountered when executing `statement`, execution of `statement` terminates, and execution continues at the statement immediately following the labeled statement.
`continue label;` can only be used if `statement` is one of the [looping statements](/en-US/docs/Web/JavaScript/Reference/Statements#iterations). If a `continue label;` statement is encountered when executing `statement`, execution of `statement` continues at the next iteration of the loop. `continue;` without a label can only continue the innermost loop, while `continue label;` allows continuing any given loop even when the statement is nested within other loops.
A statement can have multiple labels. In this case, the labels are all functionally equivalent.
## Examples
### Using a labeled continue with for loops
```js
// The first for statement is labeled "loop1"
loop1: for (let i = 0; i < 3; i++) {
// The second for statement is labeled "loop2"
loop2: for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
continue loop1;
}
console.log(`i = ${i}, j = ${j}`);
}
}
// Logs:
// i = 0, j = 0
// i = 0, j = 1
// i = 0, j = 2
// i = 1, j = 0
// i = 2, j = 0
// i = 2, j = 1
// i = 2, j = 2
```
Notice how it skips both "i = 1, j = 1" and "i = 1, j = 2".
### Using a labeled break with for loops
```js
let i, j;
// The first for statement is labeled "loop1"
loop1: for (i = 0; i < 3; i++) {
// The second for statement is labeled "loop2"
loop2: for (j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
break loop1;
}
console.log(`i = ${i}, j = ${j}`);
}
}
// Logs:
// i = 0, j = 0
// i = 0, j = 1
// i = 0, j = 2
// i = 1, j = 0
```
Notice the difference with the previous `continue` example: when `break loop1` is encountered, the execution of the outer loop is terminated, so there are no further logs beyond "i = 1, j = 0"; when `continue loop1` is encountered, the execution of the outer loop continues at the next iteration, so only "i = 1, j = 1" and "i = 1, j = 2" are skipped.
### Using a labeled continue statement
Given an array of items and an array of tests, this example counts the number of items that pass all the tests.
```js
// Numbers from 1 to 100
const items = Array.from({ length: 100 }, (_, i) => i + 1);
const tests = [
{ pass: (item) => item % 2 === 0 },
{ pass: (item) => item % 3 === 0 },
{ pass: (item) => item % 5 === 0 },
];
let itemsPassed = 0;
itemIteration: for (const item of items) {
for (const test of tests) {
if (!test.pass(item)) {
continue itemIteration;
}
}
itemsPassed++;
}
```
Note how the `continue itemIteration;` statement skips the rest of the tests for the current item as well as the statement that updates the `itemsPassed` counter, and continues with the next item. If you don't use a label, you would need to use a boolean flag instead.
```js
// Numbers from 1 to 100
const items = Array.from({ length: 100 }, (_, i) => i + 1);
const tests = [
{ pass: (item) => item % 2 === 0 },
{ pass: (item) => item % 3 === 0 },
{ pass: (item) => item % 5 === 0 },
];
let itemsPassed = 0;
for (const item of items) {
let passed = true;
for (const test of tests) {
if (!test.pass(item)) {
passed = false;
break;
}
}
if (passed) {
itemsPassed++;
}
}
```
### Using a labeled break statement
Given an array of items and an array of tests, this example determines whether all items pass all tests.
```js
// Numbers from 1 to 100
const items = Array.from({ length: 100 }, (_, i) => i + 1);
const tests = [
{ pass: (item) => item % 2 === 0 },
{ pass: (item) => item % 3 === 0 },
{ pass: (item) => item % 5 === 0 },
];
let allPass = true;
itemIteration: for (const item of items) {
for (const test of tests) {
if (!test.pass(item)) {
allPass = false;
break itemIteration;
}
}
}
```
Again, if you don't use a label, you would need to use a boolean flag instead.
```js
// Numbers from 1 to 100
const items = Array.from({ length: 100 }, (_, i) => i + 1);
const tests = [
{ pass: (item) => item % 2 === 0 },
{ pass: (item) => item % 3 === 0 },
{ pass: (item) => item % 5 === 0 },
];
let allPass = true;
for (const item of items) {
let passed = true;
for (const test of tests) {
if (!test.pass(item)) {
passed = false;
break;
}
}
if (!passed) {
allPass = false;
break;
}
}
```
### Using a labeled block with break
You can label statements other than loops, such as simple blocks, but only `break` statements can reference non-loop labels.
```js
foo: {
console.log("face");
break foo;
console.log("this will not be executed");
}
console.log("swap");
// Logs:
// "face"
// "swap"
```
### Labeled function declarations
Labels can only be applied to [statements, not declarations](/en-US/docs/Web/JavaScript/Reference/Statements#difference_between_statements_and_declarations). There is a legacy grammar that allows function declarations to be labeled in non-strict code:
```js
L: function F() {}
```
In [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode) code, however, this will throw a {{jsxref("SyntaxError")}}:
```js-nolint example-bad
"use strict";
L: function F() {}
// SyntaxError: functions cannot be labelled
```
Non-plain functions, such as [generator functions](/en-US/docs/Web/JavaScript/Reference/Statements/function*) and [async functions](/en-US/docs/Web/JavaScript/Reference/Statements/async_function) can neither be labeled in strict code, nor in non-strict code:
```js-nolint example-bad
L: function* F() {}
// SyntaxError: generator functions cannot be labelled
```
The labeled function declaration syntax is [deprecated](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features) and you should not use it, even in non-strict code. You cannot actually jump to this label within the function body.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Statements/break", "break")}}
- {{jsxref("Statements/continue", "continue")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/switch/index.md | ---
title: switch
slug: Web/JavaScript/Reference/Statements/switch
page-type: javascript-statement
browser-compat: javascript.statements.switch
---
{{jsSidebar("Statements")}}
The **`switch`** statement evaluates an [expression](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators), matching the expression's value against a series of `case` clauses, and executes [statements](/en-US/docs/Web/JavaScript/Reference/Statements) after the first `case` clause with a matching value, until a `break` statement is encountered. The `default` clause of a `switch` statement will be jumped to if no `case` matches the expression's value.
{{EmbedInteractiveExample("pages/js/statement-switch.html", "taller")}}
## Syntax
```js-nolint
switch (expression) {
case caseExpression1:
statements
case caseExpression2:
statements
// β¦
case caseExpressionN:
statements
default:
statements
}
```
- `expression`
- : An expression whose result is matched against each `case` clause.
- `case caseExpressionN` {{optional_inline}}
- : A `case` clause used to match against `expression`. If the value of `expression` matches the value of any `caseExpressionN`, execution starts from the first statement after that `case` clause until either the end of the `switch` statement or the first encountered `break`.
- `default` {{optional_inline}}
- : A `default` clause; if provided, this clause is executed if the value of `expression` doesn't match any of the `case` clauses. A `switch` statement can only have one `default` clause.
## Description
A `switch` statement first evaluates its expression. It then looks for the first `case` clause whose expression evaluates to the same value as the result of the input expression (using the [strict equality](/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality) comparison) and transfers control to that clause, executing all statements following that clause.
The clause expressions are only evaluated when necessary β if a match is already found, subsequent `case` clause expressions will not be evaluated, even when they will be visited by [fall-through](#breaking_and_fall-through).
```js
switch (undefined) {
case console.log(1):
case console.log(2):
}
// Only logs 1
```
If no matching `case` clause is found, the program looks for the optional `default` clause, and if found, transfers control to that clause, executing statements following that clause. If no `default` clause is found, the program continues execution at the statement following the end of `switch`. By convention, the `default` clause is the last clause, but it does not need to be so. A `switch` statement may only have one `default` clause; multiple `default` clauses will result in a {{jsxref("SyntaxError")}}.
### Breaking and fall-through
You can use the [`break`](/en-US/docs/Web/JavaScript/Reference/Statements/break) statement within a `switch` statement's body to break out early, often when all statements between two `case` clauses have been executed. Execution will continue at the first statement following `switch`.
If `break` is omitted, execution will proceed to the next `case` clause, even to the `default` clause, regardless of whether the value of that clause's expression matches. This behavior is called "fall-through".
```js
const foo = 0;
switch (foo) {
case -1:
console.log("negative 1");
break;
case 0: // Value of foo matches this criteria; execution starts from here
console.log(0);
// Forgotten break! Execution falls through
case 1: // no break statement in 'case 0:' so this case will run as well
console.log(1);
break; // Break encountered; will not continue into 'case 2:'
case 2:
console.log(2);
break;
default:
console.log("default");
}
// Logs 0 and 1
```
In the appropriate context, other control-flow statements also have the effect of breaking out of the `switch` statement. For example, if the `switch` statement is contained in a function, then a [`return`](/en-US/docs/Web/JavaScript/Reference/Statements/return) statement terminates the execution of the function body and therefore the `switch` statement. If the `switch` statement is contained in a loop, then a [`continue`](/en-US/docs/Web/JavaScript/Reference/Statements/continue) statement stops the `switch` statement and jumps to the next iteration of the loop.
### Lexical scoping
The `case` and `default` clauses are like [labels](/en-US/docs/Web/JavaScript/Reference/Statements/label): they indicate possible places that control flow may jump to. However, they don't create lexical [scopes](/en-US/docs/Glossary/Scope) themselves (neither do they automatically break out β as demonstrated above). For example:
```js-nolint example-bad
const action = "say_hello";
switch (action) {
case "say_hello":
const message = "hello";
console.log(message);
break;
case "say_hi":
const message = "hi";
console.log(message);
break;
default:
console.log("Empty action received.");
}
```
This example will output the error "Uncaught SyntaxError: Identifier 'message' has already been declared", because the first `const message = 'hello';` conflicts with the second `const message = 'hi';` declaration, even when they're within their own separate case clauses. Ultimately, this is due to both `const` declarations being within the same block scope created by the `switch` body.
To fix this, whenever you need to use `let` or `const` declarations in a `case` clause, wrap it in a block.
```js
const action = "say_hello";
switch (action) {
case "say_hello": {
const message = "hello";
console.log(message);
break;
}
case "say_hi": {
const message = "hi";
console.log(message);
break;
}
default: {
console.log("Empty action received.");
}
}
```
This code will now output `hello` in the console as it should, without any errors.
## Examples
### Using switch
In the following example, if `expr` evaluates to `Bananas`, the program matches the value with case `case 'Bananas'` and executes the associated statement. When `break` is encountered, the program breaks out of `switch` and executes the statement following `switch`. If `break` were omitted, the statement for the `case 'Cherries'` would also be executed.
```js
switch (expr) {
case "Oranges":
console.log("Oranges are $0.59 a pound.");
break;
case "Apples":
console.log("Apples are $0.32 a pound.");
break;
case "Bananas":
console.log("Bananas are $0.48 a pound.");
break;
case "Cherries":
console.log("Cherries are $3.00 a pound.");
break;
case "Mangoes":
case "Papayas":
console.log("Mangoes and papayas are $2.79 a pound.");
break;
default:
console.log(`Sorry, we are out of ${expr}.`);
}
console.log("Is there anything else you'd like?");
```
### Putting the default clause between two case clauses
If no match is found, execution will start from the `default` clause, and execute all statements after that.
```js
const foo = 5;
switch (foo) {
case 2:
console.log(2);
break; // it encounters this break so will not continue into 'default:'
default:
console.log("default");
// fall-through
case 1:
console.log("1");
}
```
It also works when you put `default` before all other `case` clauses.
### Taking advantage of fall-through
This method takes advantage of the fact that if there is no `break` below a `case` clause, execution will continue to the next `case` clause regardless if that `case` meets the criteria.
The following is an example of a single operation sequential `case` statement, where four different values perform exactly the same.
```js
const Animal = "Giraffe";
switch (Animal) {
case "Cow":
case "Giraffe":
case "Dog":
case "Pig":
console.log("This animal is not extinct.");
break;
case "Dinosaur":
default:
console.log("This animal is extinct.");
}
```
The following is an example of a multiple-operation sequential `case` clause, where, depending on the provided integer, you can receive different output. This shows you that it will traverse in the order that you put the `case` clauses, and it does not have to be numerically sequential. In JavaScript, you can even mix in definitions of strings into these `case` statements as well.
```js
const foo = 1;
let output = "Output: ";
switch (foo) {
case 0:
output += "So ";
case 1:
output += "What ";
output += "Is ";
case 2:
output += "Your ";
case 3:
output += "Name";
case 4:
output += "?";
console.log(output);
break;
case 5:
output += "!";
console.log(output);
break;
default:
console.log("Please pick a number from 0 to 5!");
}
```
The output from this example:
| Value | Log text |
| ----------------------------------------------------- | --------------------------------- |
| `foo` is `NaN` or not `1`, `2`, `3`, `4`, `5`, or `0` | Please pick a number from 0 to 5! |
| `0` | Output: So What Is Your Name? |
| `1` | Output: What Is Your Name? |
| `2` | Output: Your Name? |
| `3` | Output: Name? |
| `4` | Output: ? |
| `5` | Output: ! |
### An alternative to if...else chains
You may often find yourself doing a series of [`if...else`](/en-US/docs/Web/JavaScript/Reference/Statements/if...else) matches.
```js
if ("fetch" in globalThis) {
// Fetch a resource with fetch
} else if ("XMLHttpRequest" in globalThis) {
// Fetch a resource with XMLHttpRequest
} else {
// Fetch a resource with some custom AJAX logic
}
```
This pattern is not doing a sequence of `===` comparisons, but you can still convert it to a `switch` construct.
```js
switch (true) {
case "fetch" in globalThis:
// Fetch a resource with fetch
break;
case "XMLHttpRequest" in globalThis:
// Fetch a resource with XMLHttpRequest
break;
default:
// Fetch a resource with some custom AJAX logic
break;
}
```
The `switch (true)` pattern as an alternative to `if...else` is especially useful if you want to utilize the fall-through behavior.
```js
switch (true) {
case isSquare(shape):
console.log("This shape is a square.");
// Fall-through, since a square is a rectangle as well!
case isRectangle(shape):
console.log("This shape is a rectangle.");
case isQuadrilateral(shape):
console.log("This shape is a quadrilateral.");
break;
case isCircle(shape):
console.log("This shape is a circle.");
break;
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Statements/if...else", "if...else")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/var/index.md | ---
title: var
slug: Web/JavaScript/Reference/Statements/var
page-type: javascript-statement
browser-compat: javascript.statements.var
---
{{jsSidebar("Statements")}}
The **`var`** statement declares function-scoped or globally-scoped variables, optionally initializing each to a value.
{{EmbedInteractiveExample("pages/js/statement-var.html")}}
## Syntax
```js-nolint
var name1;
var name1 = value1;
var name1 = value1, name2 = value2;
var name1, name2 = value2;
var name1 = value1, name2, /* β¦, */ nameN = valueN;
```
- `nameN`
- : The name of the variable to declare. Each must be a legal JavaScript [identifier](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers) or a [destructuring binding pattern](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment).
- `valueN` {{optional_inline}}
- : Initial value of the variable. It can be any legal expression. Default value is `undefined`.
## Description
The scope of a variable declared with `var` is one of the following curly-brace-enclosed syntaxes that most closely contains the `var` statement:
- Function body
- [Static initialization block](/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks)
Or if none of the above applies:
- The current [module](/en-US/docs/Web/JavaScript/Guide/Modules), for code running in module mode
- The global scope, for code running in script mode.
```js
function foo() {
var x = 1;
function bar() {
var y = 2;
console.log(x); // 1 (function `bar` closes over `x`)
console.log(y); // 2 (`y` is in scope)
}
bar();
console.log(x); // 1 (`x` is in scope)
console.log(y); // ReferenceError, `y` is scoped to `bar`
}
foo();
```
Importantly, other block constructs, including [block statements](/en-US/docs/Web/JavaScript/Reference/Statements/block), {{jsxref("Statements/try...catch", "try...catch")}}, {{jsxref("Statements/switch", "switch")}}, headers of [one of the `for` statements](/en-US/docs/Web/JavaScript/Reference/Statements#iterations), do not create scopes for `var`, and variables declared with `var` inside such a block can continue to be referenced outside the block.
```js
for (var a of [1, 2, 3]);
console.log(a); // 3
```
In a script, a variable declared using `var` is added as a non-configurable property of the global object. This means its property descriptor cannot be changed and it cannot be deleted using {{jsxref("Operators/delete", "delete")}}. JavaScript has automatic memory management, and it would make no sense to be able to use the `delete` operator on a global variable.
```js-nolint example-bad
"use strict";
var x = 1;
Object.hasOwn(globalThis, "x"); // true
delete globalThis.x; // TypeError in strict mode. Fails silently otherwise.
delete x; // SyntaxError in strict mode. Fails silently otherwise.
```
In both NodeJS [CommonJS](https://www.commonjs.org/) modules and native [ECMAScript modules](/en-US/docs/Web/JavaScript/Guide/Modules), top-level variable declarations are scoped to the module, and are not added as properties to the global object.
The list that follows the `var` keyword is called a _{{Glossary("binding")}} list_ and is separated by commas, where the commas are _not_ [comma operators](/en-US/docs/Web/JavaScript/Reference/Operators/Comma_operator) and the `=` signs are _not_ [assignment operators](/en-US/docs/Web/JavaScript/Reference/Operators/Assignment). Initializers of later variables can refer to earlier variables in the list and get the initialized value.
### Hoisting
`var` declarations, wherever they occur in a script, are processed before any code within the script is executed. Declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called [_hoisting_](/en-US/docs/Glossary/Hoisting), as it appears that the variable declaration is moved to the top of the function, static initialization block, or script source in which it occurs.
> **Note:** `var` declarations are only hoisted to the top of the current script. If you have two `<script>` elements within one HTML, the first script cannot access variables declared by the second before the second script has been processed and executed.
```js
bla = 2;
var bla;
```
This is implicitly understood as:
```js
var bla;
bla = 2;
```
For that reason, it is recommended to always declare variables at the top of their scope (the top of global code and the top of function code) so it's clear which variables are scoped to the current function.
Only a variable's declaration is hoisted, not its initialization. The initialization happens only when the assignment statement is reached. Until then the variable remains `undefined` (but declared):
```js
function doSomething() {
console.log(bar); // undefined
var bar = 111;
console.log(bar); // 111
}
```
This is implicitly understood as:
```js
function doSomething() {
var bar;
console.log(bar); // undefined
bar = 111;
console.log(bar); // 111
}
```
### Redeclarations
Duplicate variable declarations using `var` will not trigger an error, even in strict mode, and the variable will not lose its value, unless the declaration has an initializer.
```js
var a = 1;
var a = 2;
console.log(a); // 2
var a;
console.log(a); // 2; not undefined
```
`var` declarations can also be in the same scope as a `function` declaration. In this case, the `var` declaration's initializer always overrides the function's value, regardless of their relative position. This is because function declarations are hoisted before any initializer gets evaluated, so the initializer comes later and overrides the value.
```js
var a = 1;
function a() {}
console.log(a); // 1
```
`var` declarations cannot be in the same scope as a {{jsxref("Statements/let", "let")}}, {{jsxref("Statements/const", "const")}}, {{jsxref("Statements/class", "class")}}, or {{jsxref("Statements/import", "import")}} declaration.
```js-nolint example-bad
var a = 1;
let a = 2; // SyntaxError: Identifier 'a' has already been declared
```
Because `var` declarations are not scoped to blocks, this also applies to the following case:
```js-nolint example-bad
let a = 1;
{
var a = 1; // SyntaxError: Identifier 'a' has already been declared
}
```
It does not apply to the following case, where `let` is in a child scope of `var`, not the same scope:
```js example-good
var a = 1;
{
let a = 2;
}
```
A `var` declaration within a function's body can have the same name as a parameter.
```js
function foo(a) {
var a = 1;
console.log(a);
}
foo(2); // Logs 1
```
A `var` declaration within a `catch` block can have the same name as the `catch`-bound identifier, but only if the `catch` binding is a simple identifier, not a destructuring pattern. This is a [deprecated syntax](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#statements) and you should not rely on it. In this case, the declaration is hoisted to outside the `catch` block, but any value assigned within the `catch` block is not visible outside.
```js-nolint example-bad
try {
throw 1;
} catch (e) {
var e = 2; // Works
}
console.log(e); // undefined
```
## Examples
### Declaring and initializing two variables
```js
var a = 0,
b = 0;
```
### Assigning two variables with single string value
```js
var a = "A";
var b = a;
```
This is equivalent to:
```js-nolint
var a, b = a = "A";
```
Be mindful of the order:
```js
var x = y,
y = "A";
console.log(x, y); // undefined A
```
Here, `x` and `y` are declared before any code is executed, but the assignments occur later. At the time `x = y` is evaluated, `y` exists so no `ReferenceError` is thrown and its value is `undefined`. So, `x` is assigned the undefined value. Then, `y` is assigned the value `"A"`.
### Initialization of several variables
Be careful of the `var x = y = 1` syntax β `y` is not actually declared as a variable, so `y = 1` is an [unqualified identifier assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Assignment#unqualified_identifier_assignment), which creates a global variable in non-strict mode.
```js-nolint
var x = 0;
function f() {
var x = y = 1; // Declares x locally; declares y globally.
}
f();
console.log(x, y); // 0 1
// In non-strict mode:
// x is the global one as expected;
// y is leaked outside of the function, though!
```
The same example as above but with a strict mode:
```js-nolint
"use strict";
var x = 0;
function f() {
var x = y = 1; // ReferenceError: y is not defined
}
f();
console.log(x, y);
```
### Implicit globals and outer function scope
Variables that appear to be implicit globals may be references to variables in an outer function scope:
```js
var x = 0; // Declares x within file scope, then assigns it a value of 0.
console.log(typeof z); // "undefined", since z doesn't exist yet
function a() {
var y = 2; // Declares y within scope of function a, then assigns it a value of 2.
console.log(x, y); // 0 2
function b() {
x = 3; // Assigns 3 to existing file scoped x.
y = 4; // Assigns 4 to existing outer y.
z = 5; // Creates a new global variable z, and assigns it a value of 5.
// (Throws a ReferenceError in strict mode.)
}
b(); // Creates z as a global variable.
console.log(x, y, z); // 3 4 5
}
a(); // Also calls b.
console.log(x, z); // 3 5
console.log(typeof y); // "undefined", as y is local to function a
```
### Declaration with destructuring
The left-hand side of each `=` can also be a binding pattern. This allows creating multiple variables at once.
```js
const result = /(a+)(b+)(c+)/.exec("aaabcc");
var [, a, b, c] = result;
console.log(a, b, c); // "aaa" "b" "cc"
```
For more information, see [Destructuring assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Statements/let", "let")}}
- {{jsxref("Statements/const", "const")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/if...else/index.md | ---
title: if...else
slug: Web/JavaScript/Reference/Statements/if...else
page-type: javascript-statement
browser-compat: javascript.statements.if_else
---
{{jsSidebar("Statements")}}
The **`if...else`** statement executes a statement if a specified condition is {{Glossary("truthy")}}. If the condition is {{Glossary("falsy")}}, another statement in the optional `else` clause will be executed.
{{EmbedInteractiveExample("pages/js/statement-ifelse.html")}}
## Syntax
```js-nolint
if (condition)
statement1
// With an else clause
if (condition)
statement1
else
statement2
```
- `condition`
- : An expression that is considered to be either {{Glossary("truthy")}} or {{Glossary("falsy")}}.
- `statement1`
- : Statement that is executed if _condition_ is {{Glossary("truthy")}}. Can be any statement, including further nested `if` statements. To execute multiple statements, use a [block](/en-US/docs/Web/JavaScript/Reference/Statements/block) statement (`{ /* ... */ }`) to group those statements. To execute no statements, use an [empty](/en-US/docs/Web/JavaScript/Reference/Statements/Empty) statement.
- `statement2`
- : Statement that is executed if `condition` is {{Glossary("falsy")}} and the `else` clause exists. Can be any statement, including block statements and further nested `if` statements.
## Description
Multiple `if...else` statements can be nested to create an `else if` clause. Note that there is no `elseif` (in one word) keyword in JavaScript.
```js-nolint
if (condition1)
statement1
else if (condition2)
statement2
else if (condition3)
statement3
// β¦
else
statementN
```
To see how this works, this is how it would look if the nesting were properly indented:
```js-nolint
if (condition1)
statement1
else
if (condition2)
statement2
else
if (condition3)
statement3
// β¦
```
To execute multiple statements within a clause, use a block statement (`{ /* ... */ }`) to group those statements.
```js-nolint
if (condition) {
statements1
} else {
statements2
}
```
Not using blocks may lead to confusing behavior, especially if the code is hand-formatted. For example:
```js-nolint example-bad
function checkValue(a, b) {
if (a === 1)
if (b === 2)
console.log("a is 1 and b is 2");
else
console.log("a is not 1");
}
```
This code looks innocent β however, executing `checkValue(1, 3)` will log "a is not 1". This is because in the case of [dangling else](https://en.wikipedia.org/wiki/Dangling_else), the `else` clause will be connected to the closest `if` clause. Therefore, the code above, with proper indentation, would look like:
```js-nolint
function checkValue(a, b) {
if (a === 1)
if (b === 2)
console.log("a is 1 and b is 2");
else
console.log("a is not 1");
}
```
In general, it is a good practice to always use block statements, especially in code involving nested `if` statements.
```js example-good
function checkValue(a, b) {
if (a === 1) {
if (b === 2) {
console.log("a is 1 and b is 2");
}
} else {
console.log("a is not 1");
}
}
```
Do not confuse the primitive Boolean values `true` and `false` with truthiness or falsiness of the {{jsxref("Boolean")}} object. Any value that is not `false`, `undefined`, `null`, `0`, `-0`, `NaN`, or the empty string (`""`), and any object, including a Boolean object whose value is `false`, is considered {{Glossary("truthy")}} when used as the condition. For example:
```js
const b = new Boolean(false);
if (b) {
console.log("b is truthy"); // "b is truthy"
}
```
## Examples
### Using if...else
```js
if (cipherChar === fromChar) {
result += toChar;
x++;
} else {
result += clearChar;
}
```
### Using else if
Note that there is no `elseif` syntax in JavaScript. However, you can write it with a space between `else` and `if`:
```js
if (x > 50) {
/* do something */
} else if (x > 5) {
/* do something */
} else {
/* do something */
}
```
### Using an assignment as a condition
You should almost never have an `if...else` with an assignment like `x = y` as a condition:
```js example-bad
if ((x = y)) {
// β¦
}
```
Because unlike {{jsxref("Statements/while", "while")}} loops, the condition is only evaluated once, so the assignment is only performed once. The code above is equivalent to:
```js example-good
x = y;
if (x) {
// β¦
}
```
Which is much clearer. However, in the rare case you find yourself wanting to do something like that, the [`while`](/en-US/docs/Web/JavaScript/Reference/Statements/while) documentation has a [Using an assignment as a condition](/en-US/docs/Web/JavaScript/Reference/Statements/while#using_an_assignment_as_a_condition) section with our recommendations.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Statements/block", "block")}}
- {{jsxref("Statements/switch", "switch")}}
- [Conditional (ternary) operator](/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/async_function_star_/index.md | ---
title: async function*
slug: Web/JavaScript/Reference/Statements/async_function*
page-type: javascript-statement
browser-compat: javascript.statements.async_generator_function
---
{{jsSidebar("Statements")}}
The **`async function*`** declaration creates a {{Glossary("binding")}} of a new async generator function to a given name.
You can also define async generator functions using the [`async function*` expression](/en-US/docs/Web/JavaScript/Reference/Operators/async_function*).
{{EmbedInteractiveExample("pages/js/expressions-async-function-asterisk.html", "taller")}}
## Syntax
```js-nolint
async function* name(param0) {
statements
}
async function* name(param0, param1) {
statements
}
async function* name(param0, param1, /* β¦, */ paramN) {
statements
}
```
> **Note:** Async generator functions do not have arrow function counterparts.
> **Note:** `function` and `*` are separate tokens, so they can be separated by [whitespace or line terminators](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#white_space). However, there cannot be a line terminator between `async` and `function`, otherwise a semicolon is [automatically inserted](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#automatic_semicolon_insertion), causing `async` to become an identifier and the rest to become a `function*` declaration.
### Parameters
- `name`
- : The function name.
- `param` {{optional_inline}}
- : The name of a formal parameter for the function. For the parameters' syntax, see the [Functions reference](/en-US/docs/Web/JavaScript/Guide/Functions#function_parameters).
- `statements` {{optional_inline}}
- : The statements comprising the body of the function.
## Description
An `async function*` declaration creates an {{jsxref("AsyncGeneratorFunction")}} object. Each time when an async generator function is called, it returns a new {{jsxref("AsyncGenerator")}} object, which conforms to the [async iterator protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols). Every call to `next()` returns a {{jsxref("Promise")}} that resolves to the iterator result object.
An async generator function combines the features of [async functions](/en-US/docs/Web/JavaScript/Reference/Statements/async_function) and [generator functions](/en-US/docs/Web/JavaScript/Reference/Statements/function*). You can use both the [`await`](/en-US/docs/Web/JavaScript/Reference/Operators/await) and [`yield`](/en-US/docs/Web/JavaScript/Reference/Operators/yield) keywords within the function body. This empowers you to handle asynchronous tasks ergonomically with `await`, while leveraging the lazy nature of generator functions.
When a promise is yielded from an async generator, the iterator result promise's eventual state will match that of the yielded promise. For example:
```js
async function* foo() {
yield Promise.reject(1);
}
foo()
.next()
.catch((e) => console.error(e));
```
`1` will be logged, because if the yielded promise rejects, the iterator result will reject as well. The `value` property of an async generator's resolved result will not be another promise.
`async function*` declarations behave similar to {{jsxref("Statements/function", "function")}} declarations β they are [hoisted](/en-US/docs/Glossary/Hoisting) to the top of their scope and can be called anywhere in their scope, and they can be redeclared only in certain contexts.
## Examples
### Declaring an async generator function
Async generator functions always produce promises of results β even when each `yield` step is synchronous.
```js
async function* myGenerator(step) {
await new Promise((resolve) => setTimeout(resolve, 10));
yield 0;
yield step;
yield step * 2;
}
const gen = myGenerator(2);
gen
.next()
.then((res) => {
console.log(res); // { value: 0, done: false }
return gen.next();
})
.then((res) => {
console.log(res); // { value: 2, done: false }
return gen.next();
})
.then((res) => {
console.log(res); // { value: 4, done: false }
return gen.next();
})
.then((res) => {
console.log(res); // { value: undefined, done: true }
return gen.next();
});
```
### Using an async generator function to read a series of files
In this example, we read a series of files and only access its content when requested, using Node's [`fs/promises`](https://nodejs.org/dist/latest-v18.x/docs/api/fs.html) module.
```js
async function* readFiles(directory) {
const files = await fs.readdir(directory);
for (const file of files) {
const stats = await fs.stat(file);
if (stats.isFile()) {
yield {
name: file,
content: await fs.readFile(file, "utf8"),
};
}
}
}
const files = readFiles(".");
console.log((await files.next()).value);
// Possible output: { name: 'file1.txt', content: '...' }
console.log((await files.next()).value);
// Possible output: { name: 'file2.txt', content: '...' }
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Functions](/en-US/docs/Web/JavaScript/Guide/Functions) guide
- [Iterators and generators](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators) guide
- [Functions](/en-US/docs/Web/JavaScript/Reference/Functions)
- {{jsxref("AsyncGeneratorFunction")}}
- [`async function*` expression](/en-US/docs/Web/JavaScript/Reference/Operators/async_function*)
- {{jsxref("Statements/function", "function")}}
- {{jsxref("Statements/function*", "function*")}}
- {{jsxref("Statements/async_function", "async function")}}
- [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
- {{jsxref("Operators/yield", "yield")}}
- {{jsxref("Operators/yield*", "yield*")}}
- {{jsxref("AsyncGenerator")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/throw/index.md | ---
title: throw
slug: Web/JavaScript/Reference/Statements/throw
page-type: javascript-statement
browser-compat: javascript.statements.throw
---
{{jsSidebar("Statements")}}
The **`throw`** statement throws a user-defined exception. Execution of the current function will stop (the statements after `throw` won't be executed), and control will be passed to the first [`catch`](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch) block in the call stack. If no `catch` block exists among caller functions, the program will terminate.
{{EmbedInteractiveExample("pages/js/statement-throw.html")}}
## Syntax
```js-nolint
throw expression;
```
- `expression`
- : The expression to throw.
## Description
The `throw` statement is valid in all contexts where statements can be used. Its execution generates an exception that penetrates through the call stack. For more information on error bubbling and handling, see [Control flow and error handling](/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling).
The `throw` keyword can be followed by any kind of expression, for example:
```js
throw error; // Throws a previously defined value (e.g. within a catch block)
throw new Error("Required"); // Throws a new Error object
```
In practice, the exception you throw should _always_ be an {{jsxref("Error")}} object or an instance of an `Error` subclass, such as {{jsxref("RangeError")}}. This is because code that catches the error may expect certain properties, such as {{jsxref("Error/message", "message")}}, to be present on the caught value. For example, web APIs typically throw {{domxref("DOMException")}} instances, which inherit from `Error.prototype`.
### Automatic semicolon insertion
The syntax forbids line terminators between the `throw` keyword and the expression to be thrown.
```js-nolint example-bad
throw
new Error();
```
The code above is transformed by [automatic semicolon insertion (ASI)](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#automatic_semicolon_insertion) into:
```js-nolint
throw;
new Error();
```
This is invalid code, because unlike {{jsxref("Statements/return", "return")}}, `throw` must be followed by an expression.
To avoid this problem (to prevent ASI), you could use parentheses:
```js-nolint
throw (
new Error()
);
```
## Examples
### Throwing a user-defined error
This example defines a function that throws a {{jsxref("TypeError")}} if the input is not of the expected type.
```js
function isNumeric(x) {
return ["number", "bigint"].includes(typeof x);
}
function sum(...values) {
if (!values.every(isNumeric)) {
throw new TypeError("Can only add numbers");
}
return values.reduce((a, b) => a + b);
}
console.log(sum(1, 2, 3)); // 6
try {
sum("1", "2");
} catch (e) {
console.error(e); // TypeError: Can only add numbers
}
```
### Throwing an existing object
This example calls a callback-based async function, and throws an error if the callback receives an error.
```js
readFile("foo.txt", (err, data) => {
if (err) {
throw err;
}
console.log(data);
});
```
Errors thrown this way are not catchable by the caller and will cause the program to crash unless (a) the `readFile` function itself catches the error, or (b) the program is running in a context that catches top-level errors. You can handle errors more naturally by using the {{jsxref("Promise/Promise", "Promise()")}} constructor.
```js
function readFilePromise(path) {
return new Promise((resolve, reject) => {
readFile(path, (err, data) => {
if (err) {
reject(err);
}
resolve(data);
});
});
}
try {
const data = await readFilePromise("foo.txt");
console.log(data);
} catch (err) {
console.error(err);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Statements/try...catch", "try...catch")}}
- {{jsxref("Error")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/debugger/index.md | ---
title: debugger
slug: Web/JavaScript/Reference/Statements/debugger
page-type: javascript-statement
browser-compat: javascript.statements.debugger
---
{{jsSidebar("Statements")}}
The **`debugger`** statement invokes any available debugging
functionality, such as setting a breakpoint. If no debugging functionality is available,
this statement has no effect.
## Syntax
```js-nolint
debugger;
```
## Examples
### Using the debugger statement
The following example shows code where a `debugger` statement has been
inserted, to invoke a debugger (if one exists) when the function is called.
```js
function potentiallyBuggyCode() {
debugger;
// do potentially buggy stuff to examine, step through, etc.
}
```
When the debugger is invoked, execution is paused at the `debugger`
statement. It is like a breakpoint in the script source.

## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [The Firefox JavaScript DebuggerΒΆ](https://firefox-source-docs.mozilla.org/devtools-user/debugger/index.html) in the Firefox source docs
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/continue/index.md | ---
title: continue
slug: Web/JavaScript/Reference/Statements/continue
page-type: javascript-statement
browser-compat: javascript.statements.continue
---
{{jsSidebar("Statements")}}
The **`continue`** statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
{{EmbedInteractiveExample("pages/js/statement-continue.html")}}
## Syntax
```js-nolint
continue;
continue label;
```
- `label` {{optional_inline}}
- : Identifier associated with the label of the statement.
## Description
In contrast to the {{jsxref("Statements/break", "break")}} statement, `continue` does not terminate the execution of the loop entirely, but instead:
- In a {{jsxref("Statements/while", "while")}} or {{jsxref("Statements/do...while", "do...while")}} loop, it jumps back to the condition.
- In a {{jsxref("Statements/for", "for")}} loop, it jumps to the update expression.
- In a {{jsxref("Statements/for...in", "for...in")}}, {{jsxref("Statements/for...of", "for...of")}}, or {{jsxref("Statements/for-await...of", "for await...of")}} loop, it jumps to the next iteration.
The `continue` statement can include an optional label that allows the program to jump to the next iteration of a labeled loop statement instead of the innermost loop. In this case, the `continue` statement needs to be nested within this labeled statement.
A `continue` statement, with or without a following label, cannot be used at the top level of a script, module, function's body, or [static initialization block](/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks), even when the function or class is further contained within a loop.
## Examples
### Using continue with while
The following example shows a {{jsxref("Statements/while", "while")}} loop that has a `continue` statement that executes when the value of `i` is 3. Thus, `n` takes on the values 1, 3, 7, and 12.
```js
let i = 0;
let n = 0;
while (i < 5) {
i++;
if (i === 3) {
continue;
}
n += i;
}
```
### Using continue with a label
In the following example, a statement labeled `checkIAndJ` contains a statement labeled `checkJ`. If `continue` is encountered, the program continues at the top of the `checkJ` statement. Each time `continue` is encountered, `checkJ` reiterates until its condition returns false. When false is returned, the remainder of the `checkIAndJ` statement is completed.
If `continue` had a label of `checkIAndJ`, the program would continue at the top of the `checkIAndJ` statement.
```js
let i = 0;
let j = 8;
checkIAndJ: while (i < 4) {
console.log(`i: ${i}`);
i += 1;
checkJ: while (j > 4) {
console.log(`j: ${j}`);
j -= 1;
if (j % 2 === 0) continue checkJ;
console.log(`${j} is odd.`);
}
console.log(`i = ${i}`);
console.log(`j = ${j}`);
}
```
Output:
```plain
i: 0
// start checkj
j: 8
7 is odd.
j: 7
j: 6
5 is odd.
j: 5
// end checkj
i = 1
j = 4
i: 1
i = 2
j = 4
i: 2
i = 3
j = 4
i: 3
i = 4
j = 4
```
### Unsyntactic continue statements
`continue` cannot be used within loops across function boundaries.
```js-nolint example-bad
for (let i = 0; i < 10; i++) {
(() => {
continue; // SyntaxError: Illegal continue statement: no surrounding iteration statement
})();
}
```
When referencing a label, the labeled statement must contain the `continue` statement.
```js-nolint example-bad
label: for (let i = 0; i < 10; i++) {
console.log(i);
}
for (let i = 0; i < 10; i++) {
continue label; // SyntaxError: Undefined label 'label'
}
```
The labeled statement must be a loop.
```js-nolint example-bad
label: {
for (let i = 0; i < 10; i++) {
continue label; // SyntaxError: Illegal continue statement: 'label' does not denote an iteration statement
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Statements/break", "break")}}
- {{jsxref("Statements/label", "label", "", 1)}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/statements | data/mdn-content/files/en-us/web/javascript/reference/statements/block/index.md | ---
title: Block statement
slug: Web/JavaScript/Reference/Statements/block
page-type: javascript-statement
browser-compat: javascript.statements.block
---
{{jsSidebar("Statements")}}
A **block statement** is used to group zero or more statements. The block is delimited by a pair of braces ("curly braces") and contains a list of zero or more statements and declarations.
{{EmbedInteractiveExample("pages/js/statement-block.html", "taller")}}
## Syntax
```js-nolint
{
StatementList
}
```
- `StatementList`
- : Statements and declarations grouped within the block statement.
## Description
The block statement is often called the _compound statement_ in other languages. It allows you to use multiple statements where JavaScript expects only one statement. Combining statements into blocks is a common practice in JavaScript, especially when used in association with control flow statements like {{jsxref("Statements/if...else", "if...else")}} and {{jsxref("Statements/for", "for")}}. The opposite behavior is possible using an [empty statement](/en-US/docs/Web/JavaScript/Reference/Statements/Empty), where you provide no statement, although one is required.
In addition, combined with block-scoped declarations like [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let), [`const`](/en-US/docs/Web/JavaScript/Reference/Statements/const), and [`class`](/en-US/docs/Web/JavaScript/Reference/Statements/class), blocks can prevent temporary variables from polluting the global namespace, just like [IIFEs](/en-US/docs/Glossary/IIFE) do.
### Block scoping rules with var or function declaration in non-strict mode
Variables declared with `var` or created by [function declarations](/en-US/docs/Web/JavaScript/Reference/Statements/function) in non-strict mode **do not** have block scope. Variables introduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. For example:
```js
var x = 1;
{
var x = 2;
}
console.log(x); // 2
```
This logs 2 because the `var x` statement within the block is in the same scope as the `var x` statement before the block.
In non-strict code, function declarations inside blocks behave strangely. Do not use them.
### Block scoping rules with let, const, class, or function declaration in strict mode
By contrast, identifiers declared with [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let), [`const`](/en-US/docs/Web/JavaScript/Reference/Statements/const), and [`class`](/en-US/docs/Web/JavaScript/Reference/Statements/class) do have block scope:
```js
let x = 1;
{
let x = 2;
}
console.log(x); // 1
```
The `x = 2` is limited in scope to the block in which it was defined.
The same is true of `const`:
```js
const c = 1;
{
const c = 2;
}
console.log(c); // 1; does not throw SyntaxError
```
Note that the block-scoped `const c = 2` _does not_ throw a `SyntaxError: Identifier 'c' has already been declared` because it can be declared uniquely within the block.
In [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode), function declarations inside blocks are scoped to that block and are hoisted to the top of the block.
```js
"use strict";
{
foo(); // Logs "foo"
function foo() {
console.log("foo");
}
}
foo(); // ReferenceError: foo is not defined
```
## Examples
### Using a block statement as the body of a for loop
A [`for`](/en-US/docs/Web/JavaScript/Reference/Statements/for) loop accepts a single statement as its body.
```js
for (let i = 0; i < 10; i++) console.log(i);
```
If you want to use more than one statement in the loop body, you can group them into one block statement:
```js
for (let i = 0; i < 10; i++) {
console.log(i);
console.log(i ** 2);
}
```
### Using a block statement to encapsulate data
`let` and `const` declarations are scoped to the containing block. This allows you to hide data from the global scope without wrapping it in a function.
```js
let sector;
{
// These variables are scoped to this block and are not
// accessible after the block
const angle = Math.PI / 3;
const radius = 10;
sector = {
radius,
angle,
area: (angle / 2) * radius ** 2,
perimeter: 2 * radius + angle * radius,
};
}
console.log(sector);
// {
// radius: 10,
// angle: 1.0471975511965976,
// area: 52.35987755982988,
// perimeter: 30.471975511965976
// }
console.log(typeof radius); // "undefined"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Statements/while", "while")}}
- {{jsxref("Statements/if...else", "if...else")}}
- {{jsxref("Statements/let", "let")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference | data/mdn-content/files/en-us/web/javascript/reference/iteration_protocols/index.md | ---
title: Iteration protocols
slug: Web/JavaScript/Reference/Iteration_protocols
page-type: guide
spec-urls: https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-iteration
---
{{jsSidebar("More")}}
**Iteration protocols** aren't new built-ins or syntax, but _protocols_. These protocols can be implemented by any object by following some conventions.
There are two protocols: The [iterable protocol](#the_iterable_protocol) and the [iterator protocol](#the_iterator_protocol).
## The iterable protocol
**The iterable protocol** allows JavaScript objects to define or customize their iteration behavior, such as what values are looped over in a {{jsxref("Statements/for...of", "for...of")}} construct. Some built-in types are [built-in iterables](#built-in_iterables) with a default iteration behavior, such as {{jsxref("Array")}} or {{jsxref("Map")}}, while other types (such as {{jsxref("Object")}}) are not.
In order to be **iterable**, an object must implement the **`@@iterator`** method, meaning that the object (or one of the objects up its [prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)) must have a property with a `@@iterator` key which is available via constant {{jsxref("Symbol.iterator")}}:
- `[Symbol.iterator]`
- : A zero-argument function that returns an object, conforming to the [iterator protocol](#the_iterator_protocol).
Whenever an object needs to be iterated (such as at the beginning of a {{jsxref("Statements/for...of", "for...of")}} loop), its `@@iterator` method is called with no arguments, and the returned **iterator** is used to obtain the values to be iterated.
Note that when this zero-argument function is called, it is invoked as a method on the iterable object. Therefore inside of the function, the `this` keyword can be used to access the properties of the iterable object, to decide what to provide during the iteration.
This function can be an ordinary function, or it can be a generator function, so that when invoked, an iterator object is returned. Inside of this generator function, each entry can be provided by using `yield`.
## The iterator protocol
**The iterator protocol** defines a standard way to produce a sequence of values (either finite or infinite), and potentially a return value when all values have been generated.
An object is an iterator when it implements a **`next()`** method with the following semantics:
- `next()`
- : A function that accepts zero or one argument and returns an object conforming to the `IteratorResult` interface (see below). If a non-object value gets returned (such as `false` or `undefined`) when a built-in language feature (such as `for...of`) is using the iterator, a {{jsxref("TypeError")}} (`"iterator.next() returned a non-object value"`) will be thrown.
All iterator protocol methods (`next()`, `return()`, and `throw()`) are expected to return an object implementing the `IteratorResult` interface. It must have the following properties:
- `done` {{optional_inline}}
- : A boolean that's `false` if the iterator was able to produce the next value in the sequence. (This is equivalent to not specifying the `done` property altogether.)
Has the value `true` if the iterator has completed its sequence. In this case, `value` optionally specifies the return value of the iterator.
- `value` {{optional_inline}}
- : Any JavaScript value returned by the iterator. Can be omitted when `done` is `true`.
In practice, neither property is strictly required; if an object without either property is returned, it's effectively equivalent to `{ done: false, value: undefined }`.
If an iterator returns a result with `done: true`, any subsequent calls to `next()` are expected to return `done: true` as well, although this is not enforced on the language level.
The `next` method can receive a value which will be made available to the method body. No built-in language feature will pass any value. The value passed to the `next` method of [generators](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator) will become the value of the corresponding `yield` expression.
Optionally, the iterator can also implement the **`return(value)`** and **`throw(exception)`** methods, which, when called, tells the iterator that the caller is done with iterating it and can perform any necessary cleanup (such as closing database connection).
- `return(value)` {{optional_inline}}
- : A function that accepts zero or one argument and returns an object conforming to the `IteratorResult` interface, typically with `value` equal to the `value` passed in and `done` equal to `true`. Calling this method tells the iterator that the caller does not intend to make any more `next()` calls and can perform any cleanup actions.
- `throw(exception)` {{optional_inline}}
- : A function that accepts zero or one argument and returns an object conforming to the `IteratorResult` interface, typically with `done` equal to `true`. Calling this method tells the iterator that the caller detects an error condition, and `exception` is typically an {{jsxref("Error")}} instance.
> **Note:** It is not possible to know reflectively (i.e. without actually calling `next()` and validating the returned result) whether a particular object implements the iterator protocol.
It is very easy to make an iterator also iterable: just implement an `[@@iterator]()` method that returns `this`.
```js
// Satisfies both the Iterator Protocol and Iterable
const myIterator = {
next() {
// ...
},
[Symbol.iterator]() {
return this;
},
};
```
Such object is called an _iterable iterator_. Doing so allows an iterator to be consumed by the various syntaxes expecting iterables β therefore, it is seldom useful to implement the Iterator Protocol without also implementing Iterable. (In fact, almost all syntaxes and APIs expect _iterables_, not _iterators_.) The [generator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator) is an example:
```js
const aGeneratorObject = (function* () {
yield 1;
yield 2;
yield 3;
})();
console.log(typeof aGeneratorObject.next);
// "function" β it has a next method (which returns the right result), so it's an iterator
console.log(typeof aGeneratorObject[Symbol.iterator]);
// "function" β it has an @@iterator method (which returns the right iterator), so it's an iterable
console.log(aGeneratorObject[Symbol.iterator]() === aGeneratorObject);
// true β its @@iterator method returns itself (an iterator), so it's an iterable iterator
```
All built-in iterators inherit from {{jsxref("Iterator", "Iterator.prototype")}}, which implements the `[@@iterator]()` method as returning `this`, so that built-in iterators are also iterable.
However, when possible, it's better for `iterable[Symbol.iterator]` to return different iterators that always start from the beginning, like [`Set.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/@@iterator) does.
## The async iterator and async iterable protocols
There are another pair of protocols used for async iteration, named **async iterator** and **async iterable** protocols. They have very similar interfaces compared to the iterable and iterator protocols, except that each return value from the calls to the iterator methods is wrapped in a promise.
An object implements the async iterable protocol when it implements the following methods:
- [`[Symbol.asyncIterator]`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/asyncIterator)
- : A zero-argument function that returns an object, conforming to the async iterator protocol.
An object implements the async iterator protocol when it implements the following methods:
- `next()`
- : A function that accepts zero or one argument and returns a promise. The promise fulfills to an object conforming to the `IteratorResult` interface, and the properties have the same semantics as those of the sync iterator's.
- `return(value)` {{optional_inline}}
- : A function that accepts zero or one argument and returns a promise. The promise fulfills to an object conforming to the `IteratorResult` interface, and the properties have the same semantics as those of the sync iterator's.
- `throw(exception)` {{optional_inline}}
- : A function that accepts zero or one argument and returns a promise. The promise fulfills to an object conforming to the `IteratorResult` interface, and the properties have the same semantics as those of the sync iterator's.
## Interactions between the language and iteration protocols
The language specifies APIs that either produce or consume iterables and iterators.
### Built-in iterables
{{jsxref("String")}}, {{jsxref("Array")}}, {{jsxref("TypedArray")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, and [`Segments`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment/Segments) (returned by [`Intl.Segmenter.prototype.segment()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment)) are all built-in iterables, because each of their `prototype` objects implements an `@@iterator` method. In addition, the [`arguments`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments) object and some DOM collection types such as {{domxref("NodeList")}} are also iterables.
There is no object in the core JavaScript language that is async iterable. Some web APIs, such as {{domxref("ReadableStream")}}, have the `Symbol.asyncIterator` method set by default.
[Generator functions](/en-US/docs/Web/JavaScript/Reference/Statements/function*) return [generator objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator), which are iterable iterators. [Async generator functions](/en-US/docs/Web/JavaScript/Reference/Statements/async_function*) return [async generator objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator), which are async iterable iterators.
The iterators returned from built-in iterables actually all inherit from a common class {{jsxref("Iterator")}}, which implements the aforementioned `[Symbol.iterator]() { return this; }` method, making them all iterable iterators. The `Iterator` class also provides additional [helper methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator#iterator_helpers) in addition to the `next()` method required by the iterator protocol. You can inspect an iterator's prototype chain by logging it in a graphical console.
```plain
console.log([][Symbol.iterator]());
Array Iterator {}
[[Prototype]]: Array Iterator ==> This is the prototype shared by all array iterators
next: Ζ next()
Symbol(Symbol.toStringTag): "Array Iterator"
[[Prototype]]: Object ==> This is the prototype shared by all built-in iterators
Symbol(Symbol.iterator): Ζ [Symbol.iterator]()
[[Prototype]]: Object ==> This is Object.prototype
```
### Built-in APIs accepting iterables
There are many APIs that accept iterables. Some examples include:
- {{jsxref("Map/Map", "Map()")}}
- {{jsxref("WeakMap/WeakMap", "WeakMap()")}}
- {{jsxref("Set/Set", "Set()")}}
- {{jsxref("WeakSet/WeakSet", "WeakSet()")}}
- {{jsxref("Promise.all()")}}
- {{jsxref("Promise.allSettled()")}}
- {{jsxref("Promise.race()")}}
- {{jsxref("Promise.any()")}}
- {{jsxref("Array.from()")}}
- {{jsxref("Object.groupBy()")}}
- {{jsxref("Map.groupBy()")}}
```js
const myObj = {};
new WeakSet(
(function* () {
yield {};
yield myObj;
yield {};
})(),
).has(myObj); // true
```
### Syntaxes expecting iterables
Some statements and expressions expect iterables, for example the {{jsxref("Statements/for...of", "for...of")}} loops, [array and parameter spreading](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax), {{jsxref("Operators/yield*", "yield*")}}, and [array destructuring](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment):
```js
for (const value of ["a", "b", "c"]) {
console.log(value);
}
// "a"
// "b"
// "c"
console.log([..."abc"]); // ["a", "b", "c"]
function* gen() {
yield* ["a", "b", "c"];
}
console.log(gen().next()); // { value: "a", done: false }
[a, b, c] = new Set(["a", "b", "c"]);
console.log(a); // "a"
```
When built-in syntaxes are iterating an iterator, and the last result's `done` is `false` (i.e. the iterator is able to produce more values) but no more values are needed, the `return` method will get called if present. This can happen, for example, if a `break` or `return` is encountered in a `for...of` loop, or if all identifiers are already bound in an array destructuring.
```js
const obj = {
[Symbol.iterator]() {
let i = 0;
return {
next() {
i++;
console.log("Returning", i);
if (i === 3) return { done: true, value: i };
return { done: false, value: i };
},
return() {
console.log("Closing");
return { done: true };
},
};
},
};
const [a] = obj;
// Returning 1
// Closing
const [b, c, d] = obj;
// Returning 1
// Returning 2
// Returning 3
// Already reached the end (the last call returned `done: true`),
// so `return` is not called
for (const b of obj) {
break;
}
// Returning 1
// Closing
```
The [`for await...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of) loop and [`yield*`](/en-US/docs/Web/JavaScript/Reference/Operators/yield*) in [async generator functions](/en-US/docs/Web/JavaScript/Reference/Statements/async_function*) (but not [sync generator functions](/en-US/docs/Web/JavaScript/Reference/Statements/function*)) are the only ways to interact with async iterables. Using `for...of`, array spreading, etc. on an async iterable that's not also a sync iterable (i.e. it has `[@@asyncIterator]()` but no `[@@iterator]()`) will throw a TypeError: x is not iterable.
### Non-well-formed iterables
If an iterable's `@@iterator` method doesn't return an iterator object, then it's considered a _non-well-formed_ iterable.
Using one is likely to result in runtime errors or buggy behavior:
```js example-bad
const nonWellFormedIterable = {};
nonWellFormedIterable[Symbol.iterator] = () => 1;
[...nonWellFormedIterable]; // TypeError: [Symbol.iterator]() returned a non-object value
```
## Examples
### User-defined iterables
You can make your own iterables like this:
```js
const myIterable = {
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
},
};
console.log([...myIterable]); // [1, 2, 3]
```
### Simple iterator
Iterators are stateful by nature. If you don't define it as a [generator function](/en-US/docs/Web/JavaScript/Reference/Statements/function*) (as the example above shows), you would likely want to encapsulate the state in a closure.
```js
function makeIterator(array) {
let nextIndex = 0;
return {
next() {
return nextIndex < array.length
? {
value: array[nextIndex++],
done: false,
}
: {
done: true,
};
},
};
}
const it = makeIterator(["yo", "ya"]);
console.log(it.next().value); // 'yo'
console.log(it.next().value); // 'ya'
console.log(it.next().done); // true
```
### Infinite iterator
```js
function idMaker() {
let index = 0;
return {
next() {
return {
value: index++,
done: false,
};
},
};
}
const it = idMaker();
console.log(it.next().value); // 0
console.log(it.next().value); // 1
console.log(it.next().value); // 2
// ...
```
### Defining an iterable with a generator
```js
function* makeSimpleGenerator(array) {
let nextIndex = 0;
while (nextIndex < array.length) {
yield array[nextIndex++];
}
}
const gen = makeSimpleGenerator(["yo", "ya"]);
console.log(gen.next().value); // 'yo'
console.log(gen.next().value); // 'ya'
console.log(gen.next().done); // true
function* idMaker() {
let index = 0;
while (true) {
yield index++;
}
}
const it = idMaker();
console.log(it.next().value); // 0
console.log(it.next().value); // 1
console.log(it.next().value); // 2
// ...
```
### Defining an iterable with a class
State encapsulation can be done with [private properties](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties) as well.
```js
class SimpleClass {
#data;
constructor(data) {
this.#data = data;
}
[Symbol.iterator]() {
// Use a new index for each iterator. This makes multiple
// iterations over the iterable safe for non-trivial cases,
// such as use of break or nested looping over the same iterable.
let index = 0;
return {
// Note: using an arrow function allows `this` to point to the
// one of `[@@iterator]()` instead of `next()`
next: () => {
if (index < this.#data.length) {
return { value: this.#data[index++], done: false };
} else {
return { done: true };
}
},
};
}
}
const simple = new SimpleClass([1, 2, 3, 4, 5]);
for (const val of simple) {
console.log(val); // 1 2 3 4 5
}
```
### Overriding built-in iterables
For example, a {{jsxref("String")}} is a built-in iterable object:
```js
const someString = "hi";
console.log(typeof someString[Symbol.iterator]); // "function"
```
`String`'s [default iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/@@iterator) returns the string's code points one by one:
```js
const iterator = someString[Symbol.iterator]();
console.log(`${iterator}`); // "[object String Iterator]"
console.log(iterator.next()); // { value: "h", done: false }
console.log(iterator.next()); // { value: "i", done: false }
console.log(iterator.next()); // { value: undefined, done: true }
```
You can redefine the iteration behavior by supplying our own `@@iterator`:
```js
// need to construct a String object explicitly to avoid auto-boxing
const someString = new String("hi");
someString[Symbol.iterator] = function () {
return {
// this is the iterator object, returning a single element (the string "bye")
next() {
return this._first
? { value: "bye", done: (this._first = false) }
: { done: true };
},
_first: true,
};
};
```
Notice how redefining `@@iterator` affects the behavior of built-in constructs that use the iteration protocol:
```js
console.log([...someString]); // ["bye"]
console.log(`${someString}`); // "hi"
```
## Specifications
{{Specifications}}
## See also
- [Iterators and generators](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators) guide
- {{jsxref("Statements/function*", "function*")}}
- {{jsxref("Symbol.iterator")}}
- {{jsxref("Iterator")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference | data/mdn-content/files/en-us/web/javascript/reference/lexical_grammar/index.md | ---
title: Lexical grammar
slug: Web/JavaScript/Reference/Lexical_grammar
page-type: guide
browser-compat: javascript.grammar
spec-urls: https://tc39.es/ecma262/multipage/ecmascript-language-lexical-grammar.html
---
{{jsSidebar("More")}}
This page describes JavaScript's lexical grammar. JavaScript source text is just a sequence of characters β in order for the interpreter to understand it, the string has to be _parsed_ to a more structured representation. The initial step of parsing is called [lexical analysis](https://en.wikipedia.org/wiki/Lexical_analysis), in which the text gets scanned from left to right and is converted into a sequence of individual, atomic input elements. Some input elements are insignificant to the interpreter, and will be stripped after this step β they include [white space](#white_space) and [comments](#comments). The others, including [identifiers](#identifiers), [keywords](#keywords), [literals](#literals), and punctuators (mostly [operators](/en-US/docs/Web/JavaScript/Reference/Operators)), will be used for further syntax analysis. [Line terminators](#line_terminators) and multiline comments are also syntactically insignificant, but they guide the process for [automatic semicolons insertion](#automatic_semicolon_insertion) to make certain invalid token sequences become valid.
## Format-control characters
Format-control characters have no visual representation but are used to control the interpretation of the text.
| Code point | Name | Abbreviation | Description |
| ---------- | --------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| U+200C | Zero width non-joiner | \<ZWNJ> | Placed between characters to prevent being connected into ligatures in certain languages ([Wikipedia](https://en.wikipedia.org/wiki/Zero-width_non-joiner)). |
| U+200D | Zero width joiner | \<ZWJ> | Placed between characters that would not normally be connected in order to cause the characters to be rendered using their connected form in certain languages ([Wikipedia](https://en.wikipedia.org/wiki/Zero-width_joiner)). |
| U+FEFF | Byte order mark | \<BOM> | Used at the start of the script to mark it as Unicode and the text's byte order ([Wikipedia](https://en.wikipedia.org/wiki/Byte_order_mark)). |
In JavaScript source text, \<ZWNJ> and \<ZWJ> are treated as [identifier](#identifiers) parts, while \<BOM> (also called a zero-width no-break space \<ZWNBSP> when not at the start of text) is treated as [white space](#white_space).
## White space
[White space](/en-US/docs/Glossary/Whitespace) characters improve the readability of source text and separate tokens from each other. These characters are usually unnecessary for the functionality of the code. [Minification tools](https://en.wikipedia.org/wiki/Minification_%28programming%29) are often used to remove whitespace in order to reduce the amount of data that needs to be transferred.
| Code point | Name | Abbreviation | Description | Escape sequence |
| ---------- | ------------------------------ | ------------ | -------------------------------------------------------------------------------------------------- | --------------- |
| U+0009 | Character tabulation | \<TAB> | Horizontal tabulation | \t |
| U+000B | Line tabulation | \<VT> | Vertical tabulation | \v |
| U+000C | Form feed | \<FF> | Page breaking control character ([Wikipedia](https://en.wikipedia.org/wiki/Page_break#Form_feed)). | \f |
| U+0020 | Space | \<SP> | Normal space | |
| U+00A0 | No-break space | \<NBSP> | Normal space, but no point at which a line may break | |
| U+FEFF | Zero-width no-break space | \<ZWNBSP> | When not at the start of a script, the BOM marker is a normal whitespace character. | |
| Others | Other Unicode space characters | \<USP> | [Characters in the "Space_Separator" general category][space separator set] | |
[space separator set]: https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5Cp%7BGeneral_Category%3DSpace_Separator%7D
> **Note:** Of those [characters with the "White_Space" property but are not in the "Space_Separator" general category](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5Cp%7BWhite_Space%7D%26%5CP%7BGeneral_Category%3DSpace_Separator%7D), U+0009, U+000B, and U+000C are still treated as white space in JavaScript; U+0085 NEXT LINE has no special role; others become the set of [line terminators](#line_terminators).
> **Note:** Changes to the Unicode standard used by the JavaScript engine may affect programs' behavior. For example, ES2016 upgraded the reference Unicode standard from 5.1 to 8.0.0, which caused U+180E MONGOLIAN VOWEL SEPARATOR to be moved from the "Space_Separator" category to the "Format (Cf)" category, and made it a non-whitespace. Subsequently, the result of [`"\u180E".trim().length`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim) changed from `0` to `1`.
## Line terminators
In addition to [white space](#white_space) characters, line terminator characters are used to improve the readability of the source text. However, in some cases, line terminators can influence the execution of JavaScript code as there are a few places where they are forbidden. Line terminators also affect the process of [automatic semicolon insertion](#automatic_semicolon_insertion).
Outside the context of lexical grammar, white space and line terminators are often conflated. For example, {{jsxref("String.prototype.trim()")}} removes all white space and line terminators from the beginning and end of a string. The `\s` [character class escape](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes) in regular expressions matches all white space and line terminators.
Only the following Unicode code points are treated as line terminators in ECMAScript, other line breaking characters are treated as white space (for example, Next Line, NEL, U+0085 is considered as white space).
| Code point | Name | Abbreviation | Description | Escape sequence |
| ---------- | ------------------- | ------------ | ------------------------------------------------------ | --------------- |
| U+000A | Line Feed | \<LF> | New line character in UNIX systems. | \n |
| U+000D | Carriage Return | \<CR> | New line character in Commodore and early Mac systems. | \r |
| U+2028 | Line Separator | \<LS> | [Wikipedia](https://en.wikipedia.org/wiki/Newline) | |
| U+2029 | Paragraph Separator | \<PS> | [Wikipedia](https://en.wikipedia.org/wiki/Newline) | |
## Comments
Comments are used to add hints, notes, suggestions, or warnings to JavaScript code. This can make it easier to read and understand. They can also be used to disable code to prevent it from being executed; this can be a valuable debugging tool.
JavaScript has two long-standing ways to add comments to code: line comments and block comments. In addition, there's a special hashbang comment syntax.
### Line comments
The first way is the `//` comment; this makes all text following it on the same line into a comment. For example:
```js
function comment() {
// This is a one line JavaScript comment
console.log("Hello world!");
}
comment();
```
### Block comments
The second way is the `/* */` style, which is much more flexible.
For example, you can use it on a single line:
```js
function comment() {
/* This is a one line JavaScript comment */
console.log("Hello world!");
}
comment();
```
You can also make multiple-line comments, like this:
```js
function comment() {
/* This comment spans multiple lines. Notice
that we don't need to end the comment until we're done. */
console.log("Hello world!");
}
comment();
```
You can also use it in the middle of a line, if you wish, although this can make your code harder to read so it should be used with caution:
```js
function comment(x) {
console.log("Hello " + x /* insert the value of x */ + " !");
}
comment("world");
```
In addition, you can use it to disable code to prevent it from running, by wrapping code in a comment, like this:
```js
function comment() {
/* console.log("Hello world!"); */
}
comment();
```
In this case, the `console.log()` call is never issued, since it's inside a comment. Any number of lines of code can be disabled this way.
Block comments that contain at least one line terminator behave like [line terminators](#line_terminators) in [automatic semicolon insertion](#automatic_semicolon_insertion).
### Hashbang comments
There's a special third comment syntax, the **hashbang comment**. A hashbang comment behaves exactly like a single line-only (`//`) comment, except that it begins with `#!` and **is only valid at the absolute start of a script or module**. Note also that no whitespace of any kind is permitted before the `#!`. The comment consists of all the characters after `#!` up to the end of the first line; only one such comment is permitted.
Hashbang comments in JavaScript resemble [shebangs in Unix](<https://en.wikipedia.org/wiki/Shebang_(Unix)>) which provide the path to a specific JavaScript interpreter that you want to use to execute the script. Before the hashbang comment became standardized, it had already been de-facto implemented in non-browser hosts like Node.js, where it was stripped from the source text before being passed to the engine. An example is as follows:
```js
#!/usr/bin/env node
console.log("Hello world");
```
The JavaScript interpreter will treat it as a normal comment β it only has semantic meaning to the shell if the script is directly run in a shell.
> **Warning:** If you want scripts to be runnable directly in a shell environment, encode them in UTF-8 without a [BOM](https://en.wikipedia.org/wiki/Byte_order_mark). Although a BOM will not cause any problems for code running in a browser β because it's stripped during UTF-8 decoding, before the source text is analyzed β a Unix/Linux shell will not recognize the hashbang if it's preceded by a BOM character.
You must only use the `#!` comment style to specify a JavaScript interpreter. In all other cases just use a `//` comment (or multiline comment).
## Identifiers
An _identifier_ is used to link a value with a name. Identifiers can be used in various places:
```js
const decl = 1; // Variable declaration (may also be `let` or `var`)
function fn() {} // Function declaration
const obj = { key: "value" }; // Object keys
// Class declaration
class C {
#priv = "value"; // Private property
}
lbl: console.log(1); // Label
```
In JavaScript, identifiers are commonly made of alphanumeric characters, underscores (`_`), and dollar signs (`$`). Identifiers are not allowed to start with numbers. However, JavaScript identifiers are not only limited to {{Glossary("ASCII")}} β many Unicode code points are allowed as well. Namely, any character in the [ID_Start](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5Cp%7BID_Start%7D) category can start an identifier, while any character in the [ID_Continue](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5Cp%7BID_Continue%7D) category can appear after the first character.
> **Note:** If, for some reason, you need to parse some JavaScript source yourself, do not assume all identifiers follow the pattern `/[A-Za-z_$][\w$]*/` (i.e. ASCII-only)! The range of identifiers can be described by the regex `/[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*/u` (excluding unicode escape sequences).
In addition, JavaScript allows using [Unicode escape sequences](#unicode_escape_sequences) in the form of `\u0000` or `\u{000000}` in identifiers, which encode the same string value as the actual Unicode characters. For example, `δ½ ε₯½` and `\u4f60\u597d` are the same identifiers:
```js-nolint
const δ½ ε₯½ = "Hello";
console.log(\u4f60\u597d); // Hello
```
Not all places accept the full range of identifiers. Certain syntaxes, such as function declarations, function expressions, and variable declarations require using identifiers names that are not [reserved words](#reserved_words).
```js-nolint example-bad
function import() {} // Illegal: import is a reserved word.
```
Most notably, private properties and object properties allow reserved words.
```js
const obj = { import: "value" }; // Legal despite `import` being reserved
class C {
#import = "value";
}
```
## Keywords
_Keywords_ are tokens that look like identifiers but have special meanings in JavaScript. For example, the keyword [`async`](/en-US/docs/Web/JavaScript/Reference/Statements/async_function) before a function declaration indicates that the function is asynchronous.
Some keywords are _reserved_, meaning that they cannot be used as an identifier for variable declarations, function declarations, etc. They are often called _reserved words_. [A list of these reserved words](#reserved_words) is provided below. Not all keywords are reserved β for example, `async` can be used as an identifier anywhere. Some keywords are only _contextually reserved_ β for example, `await` is only reserved within the body of an async function, and `let` is only reserved in strict mode code, or `const` and `let` declarations.
Identifiers are always compared by _string value_, so escape sequences are interpreted. For example, this is still a syntax error:
```js-nolint example-bad
const els\u{65} = 1;
// `els\u{65}` encodes the same identifier as `else`
```
### Reserved words
These keywords cannot be used as identifiers for variables, functions, classes, etc. anywhere in JavaScript source.
- {{jsxref("Statements/break", "break")}}
- {{jsxref("Statements/switch", "case")}}
- {{jsxref("Statements/try...catch", "catch")}}
- {{jsxref("Statements/class", "class")}}
- {{jsxref("Statements/const", "const")}}
- {{jsxref("Statements/continue", "continue")}}
- {{jsxref("Statements/debugger", "debugger")}}
- {{jsxref("Statements/switch", "default")}}
- {{jsxref("Operators/delete", "delete")}}
- {{jsxref("Statements/do...while", "do")}}
- {{jsxref("Statements/if...else", "else")}}
- {{jsxref("Statements/export", "export")}}
- [`extends`](/en-US/docs/Web/JavaScript/Reference/Classes/extends)
- [`false`](#boolean_literal)
- {{jsxref("Statements/try...catch", "finally")}}
- {{jsxref("Statements/for", "for")}}
- {{jsxref("Statements/function", "function")}}
- {{jsxref("Statements/if...else", "if")}}
- {{jsxref("Statements/import", "import")}}
- {{jsxref("Operators/in", "in")}}
- {{jsxref("Operators/instanceof", "instanceof")}}
- {{jsxref("Operators/new", "new")}}
- {{jsxref("Operators/null", "null")}}
- {{jsxref("Statements/return", "return")}}
- {{jsxref("Operators/super", "super")}}
- {{jsxref("Statements/switch", "switch")}}
- {{jsxref("Operators/this", "this")}}
- {{jsxref("Statements/throw", "throw")}}
- [`true`](#boolean_literal)
- {{jsxref("Statements/try...catch", "try")}}
- {{jsxref("Operators/typeof", "typeof")}}
- {{jsxref("Statements/var", "var")}}
- {{jsxref("Operators/void", "void")}}
- {{jsxref("Statements/while", "while")}}
- {{jsxref("Statements/with", "with")}}
The following are only reserved when they are found in strict mode code:
- {{jsxref("Statements/let", "let")}} (also reserved in `const`, `let`, and class declarations)
- [`static`](/en-US/docs/Web/JavaScript/Reference/Classes/static)
- {{jsxref("Operators/yield", "yield")}} (also reserved in generator function bodies)
The following are only reserved when they are found in module code or async function bodies:
- [`await`](/en-US/docs/Web/JavaScript/Reference/Operators/await)
### Future reserved words
The following are reserved as future keywords by the ECMAScript specification. They have no special functionality at present, but they might at some future time, so they cannot be used as identifiers.
These are always reserved:
- `enum`
The following are only reserved when they are found in strict mode code:
- `implements`
- `interface`
- `package`
- `private`
- `protected`
- `public`
#### Future reserved words in older standards
The following are reserved as future keywords by older ECMAScript specifications (ECMAScript 1 till 3).
- `abstract`
- `boolean`
- `byte`
- `char`
- `double`
- `final`
- `float`
- `goto`
- `int`
- `long`
- `native`
- `short`
- `synchronized`
- `throws`
- `transient`
- `volatile`
### Identifiers with special meanings
A few identifiers have a special meaning in some contexts without being reserved words of any kind. They include:
- {{jsxref("Functions/arguments", "arguments")}} (not a keyword, but cannot be declared as identifier in strict mode)
- `as` ([`import * as ns from "mod"`](/en-US/docs/Web/JavaScript/Reference/Statements/import#namespace_import))
- [`async`](/en-US/docs/Web/JavaScript/Reference/Statements/async_function)
- {{jsxref("Global_Objects/eval", "eval")}} (not a keyword, but cannot be declared as identifier in strict mode)
- `from` ([`import x from "mod"`](/en-US/docs/Web/JavaScript/Reference/Statements/import))
- {{jsxref("Functions/get", "get")}}
- [`of`](/en-US/docs/Web/JavaScript/Reference/Statements/for...of)
- {{jsxref("Functions/set", "set")}}
## Literals
> **Note:** This section discusses literals that are atomic tokens. [Object literals](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) and [array literals](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Array#array_literal_notation) are [expressions](/en-US/docs/Web/JavaScript/Reference/Operators) that consist of a series of tokens.
### Null literal
See also [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) for more information.
```js-nolint
null
```
### Boolean literal
See also [boolean type](/en-US/docs/Web/JavaScript/Data_structures#boolean_type) for more information.
```js-nolint
true
false
```
### Numeric literals
The [Number](/en-US/docs/Web/JavaScript/Data_structures#number_type) and [BigInt](/en-US/docs/Web/JavaScript/Data_structures#bigint_type) types use numeric literals.
#### Decimal
```js-nolint
1234567890
42
```
Decimal literals can start with a zero (`0`) followed by another decimal digit, but if all digits after the leading `0` are smaller than 8, the number is interpreted as an octal number. This is considered a legacy syntax, and number literals prefixed with `0`, whether interpreted as octal or decimal, cause a syntax error in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode#legacy_octal_literals) β so, use the `0o` prefix instead.
```js-nolint example-bad
0888 // 888 parsed as decimal
0777 // parsed as octal, 511 in decimal
```
##### Exponential
The decimal exponential literal is specified by the following format: `beN`; where `b` is a base number (integer or floating), followed by an `E` or `e` character (which serves as separator or _exponent indicator_) and `N`, which is _exponent_ or _power_ number β a signed integer.
```js-nolint
0e-5 // 0
0e+5 // 0
5e1 // 50
175e-2 // 1.75
1e3 // 1000
1e-3 // 0.001
1E3 // 1000
```
#### Binary
Binary number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "B" (`0b` or `0B`). Any character after the `0b` that is not 0 or 1 will terminate the literal sequence.
```js-nolint
0b10000000000000000000000000000000 // 2147483648
0b01111111100000000000000000000000 // 2139095040
0B00000000011111111111111111111111 // 8388607
```
#### Octal
Octal number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "O" (`0o` or `0O)`. Any character after the `0o` that is outside the range (01234567) will terminate the literal sequence.
```js-nolint
0O755 // 493
0o644 // 420
```
#### Hexadecimal
Hexadecimal number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "X" (`0x` or `0X`). Any character after the `0x` that is outside the range (0123456789ABCDEF) will terminate the literal sequence.
```js-nolint
0xFFFFFFFFFFFFFFFFF // 295147905179352830000
0x123456789ABCDEF // 81985529216486900
0XA // 10
```
#### BigInt literal
The [BigInt](/en-US/docs/Web/JavaScript/Data_structures#bigint_type) type is a numeric primitive in JavaScript that can represent integers with arbitrary precision. BigInt literals are created by appending `n` to the end of an integer.
```js-nolint
123456789123456789n // 123456789123456789
0o777777777777n // 68719476735
0x123456789ABCDEFn // 81985529216486895
0b11101001010101010101n // 955733
```
BigInt literals cannot start with `0` to avoid confusion with legacy octal literals.
```js-nolint example-bad
0755n; // SyntaxError: invalid BigInt syntax
```
For octal `BigInt` numbers, always use zero followed by the letter "o" (uppercase or lowercase):
```js example-good
0o755n;
```
For more information about `BigInt`, see also [JavaScript data structures](/en-US/docs/Web/JavaScript/Data_structures#bigint_type).
#### Numeric separators
To improve readability for numeric literals, underscores (`_`, `U+005F`) can be used as separators:
```js-nolint
1_000_000_000_000
1_050.95
0b1010_0001_1000_0101
0o2_2_5_6
0xA0_B0_C0
1_000_000_000_000_000_000_000n
```
Note these limitations:
```js-nolint example-bad
// More than one underscore in a row is not allowed
100__000; // SyntaxError
// Not allowed at the end of numeric literals
100_; // SyntaxError
// Can not be used after leading 0
0_1; // SyntaxError
```
### String literals
A [string](/en-US/docs/Web/JavaScript/Data_structures#string_type) literal is zero or more Unicode code points enclosed in single or double quotes. Unicode code points may also be represented by an escape sequence. All code points may appear literally in a string literal except for these code points:
- U+005C \ (backslash)
- U+000D \<CR>
- U+000A \<LF>
- The same kind of quote that begins the string literal
Any code points may appear in the form of an escape sequence. String literals evaluate to ECMAScript String values. When generating these String values Unicode code points are UTF-16 encoded.
```js-nolint
'foo'
"bar"
```
The following subsections describe various escape sequences (`\` followed by one or more characters) available in string literals. Any escape sequence not listed below becomes an "identity escape" that becomes the code point itself. For example, `\z` is the same as `z`. There's a deprecated octal escape sequence syntax described in the [Deprecated and obsolete features](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#escape_sequences) page. Many of these escape sequences are also valid in regular expressions β see [Character escape](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape).
#### Escape sequences
Special characters can be encoded using escape sequences:
| Escape sequence | Unicode code point |
| ------------------------------------------------------ | -------------------------------------------- |
| `\0` | null character (U+0000 NULL) |
| `\'` | single quote (U+0027 APOSTROPHE) |
| `\"` | double quote (U+0022 QUOTATION MARK) |
| `\\` | backslash (U+005C REVERSE SOLIDUS) |
| `\n` | newline (U+000A LINE FEED; LF) |
| `\r` | carriage return (U+000D CARRIAGE RETURN; CR) |
| `\v` | vertical tab (U+000B LINE TABULATION) |
| `\t` | tab (U+0009 CHARACTER TABULATION) |
| `\b` | backspace (U+0008 BACKSPACE) |
| `\f` | form feed (U+000C FORM FEED) |
| `\` followed by a [line terminator](#line_terminators) | empty string |
The last escape sequence, `\` followed by a line terminator, is useful for splitting a string literal across multiple lines without changing its meaning.
```js
const longString =
"This is a very long string which needs \
to wrap across multiple lines because \
otherwise my code is unreadable.";
```
Make sure there is no space or any other character after the backslash (except for a line break), otherwise it will not work. If the next line is indented, the extra spaces will also be present in the string's value.
You can also use the [`+`](/en-US/docs/Web/JavaScript/Reference/Operators/Addition) operator to append multiple strings together, like this:
```js
const longString =
"This is a very long string which needs " +
"to wrap across multiple lines because " +
"otherwise my code is unreadable.";
```
Both of the above methods result in identical strings.
#### Hexadecimal escape sequences
Hexadecimal escape sequences consist of `\x` followed by exactly two hexadecimal digits representing a code unit or code point in the range 0x0000 to 0x00FF.
```js
"\xA9"; // "Β©"
```
#### Unicode escape sequences
A Unicode escape sequence consists of exactly four hexadecimal digits following `\u`. It represents a code unit in the UTF-16 encoding. For code points U+0000 to U+FFFF, the code unit is equal to the code point. Code points U+10000 to U+10FFFF require two escape sequences representing the two code units (a surrogate pair) used to encode the character; the surrogate pair is distinct from the code point.
See also {{jsxref("String.fromCharCode()")}} and {{jsxref("String.prototype.charCodeAt()")}}.
```js
"\u00A9"; // "Β©" (U+A9)
```
#### Unicode code point escapes
A Unicode code point escape consists of `\u{`, followed by a code point in hexadecimal base, followed by `}`. The value of the hexadecimal digits must be in the range 0 and 0x10FFFF inclusive. Code points in the range U+10000 to U+10FFFF do not need to be represented as a surrogate pair.
See also {{jsxref("String.fromCodePoint()")}} and {{jsxref("String.prototype.codePointAt()")}}.
```js
"\u{2F804}"; // CJK COMPATIBILITY IDEOGRAPH-2F804 (U+2F804)
// the same character represented as a surrogate pair
"\uD87E\uDC04";
```
### Regular expression literals
Regular expression literals are enclosed by two forward slashes (`/`). The lexer consumes all characters up to the next unescaped forward slash or the end of the line, unless the forward slash appears within a character class (`[]`). Some characters (namely, those that are [identifier parts](#identifiers)) can appear after the closing slash, denoting flags.
The lexical grammar is very lenient: not all regular expression literals that get identified as one token are valid regular expressions.
See also {{jsxref("RegExp")}} for more information.
```js-nolint
/ab+c/g
/[/]/
```
A regular expression literal cannot start with two forward slashes (`//`), because that would be a line comment. To specify an empty regular expression, use `/(?:)/`.
### Template literals
One template literal consists of several tokens: `` `xxx${`` (template head), `}xxx${` (template middle), and ``}xxx` `` (template tail) are individual tokens, while any expression may come between them.
See also [template literals](/en-US/docs/Web/JavaScript/Reference/Template_literals) for more information.
```js-nolint
`string text`
`string text line 1
string text line 2`
`string text ${expression} string text`
tag`string text ${expression} string text`
```
## Automatic semicolon insertion
Some [JavaScript statements](/en-US/docs/Web/JavaScript/Reference/Statements)' syntax definitions require semicolons (`;`) at the end. They include:
- [`var`](/en-US/docs/Web/JavaScript/Reference/Statements/var), [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let), [`const`](/en-US/docs/Web/JavaScript/Reference/Statements/const)
- [Expression statements](/en-US/docs/Web/JavaScript/Reference/Statements/Expression_statement)
- [`do...while`](/en-US/docs/Web/JavaScript/Reference/Statements/do...while)
- [`continue`](/en-US/docs/Web/JavaScript/Reference/Statements/continue), [`break`](/en-US/docs/Web/JavaScript/Reference/Statements/break), [`return`](/en-US/docs/Web/JavaScript/Reference/Statements/return), [`throw`](/en-US/docs/Web/JavaScript/Reference/Statements/throw)
- [`debugger`](/en-US/docs/Web/JavaScript/Reference/Statements/debugger)
- Class field declarations ([public](/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields) or [private](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties))
- [`import`](/en-US/docs/Web/JavaScript/Reference/Statements/import), [`export`](/en-US/docs/Web/JavaScript/Reference/Statements/export)
However, to make the language more approachable and convenient, JavaScript is able to automatically insert semicolons when consuming the token stream, so that some invalid token sequences can be "fixed" to valid syntax. This step happens after the program text has been parsed to tokens according to the lexical grammar. There are three cases when semicolons are automatically inserted:
1\. When a token not allowed by the grammar is encountered, and it's separated from the previous token by at least one [line terminator](#line_terminators) (including a block comment that includes at least one line terminator), or the token is "}", then a semicolon is inserted before the token.
```js-nolint
{ 1
2 } 3
// is transformed by ASI into:
{ 1
;2 ;} 3;
// Which is valid grammar encoding three statements,
// each consisting of a number literal
```
The ending ")" of [`do...while`](/en-US/docs/Web/JavaScript/Reference/Statements/do...while) is taken care of as a special case by this rule as well.
```js-nolint
do {
// ...
} while (condition) /* ; */ // ASI here
const a = 1
```
However, semicolons are not inserted if the semicolon would then become the separator in the [`for`](/en-US/docs/Web/JavaScript/Reference/Statements/for) statement's head.
```js-nolint example-bad
for (
let a = 1 // No ASI here
a < 10 // No ASI here
a++
) {}
```
Semicolons are also never inserted as [empty statements](/en-US/docs/Web/JavaScript/Reference/Statements/Empty). For example, in the code below, if a semicolon is inserted after ")", then the code would be valid, with an empty statement as the `if` body and the `const` declaration being a separate statement. However, because automatically inserted semicolons cannot become empty statements, this causes a [declaration](/en-US/docs/Web/JavaScript/Reference/Statements#difference_between_statements_and_declarations) to become the body of the `if` statement, which is not valid.
```js-nolint example-bad
if (Math.random() > 0.5)
const x = 1 // SyntaxError: Unexpected token 'const'
```
2\. When the end of the input stream of tokens is reached, and the parser is unable to parse the single input stream as a complete program, a semicolon is inserted at the end.
```js-nolint
const a = 1 /* ; */ // ASI here
```
This rule is a complement to the previous rule, specifically for the case where there's no "offending token" but the end of input stream.
3\. When the grammar forbids line terminators in some place but a line terminator is found, a semicolon is inserted. These places include:
- `expr <here> ++`, `expr <here> --`
- `continue <here> lbl`
- `break <here> lbl`
- `return <here> expr`
- `throw <here> expr`
- `yield <here> expr`
- `yield <here> * expr`
- `(param) <here> => {}`
- `async <here> function`, `async <here> prop()`, `async <here> function*`, `async <here> *prop()`, `async <here> (param) <here> => {}`
Here [`++`](/en-US/docs/Web/JavaScript/Reference/Operators/Increment) is not treated as a postfix operator applying to variable `b`, because a line terminator occurs between `b` and `++`.
```js-nolint
a = b
++c
// is transformed by ASI into
a = b;
++c;
```
Here, the `return` statement returns `undefined`, and the `a + b` becomes an unreachable statement.
```js-nolint
return
a + b
// is transformed by ASI into
return;
a + b;
```
Note that ASI would only be triggered if a line break separates tokens that would otherwise produce invalid syntax. If the next token can be parsed as part of a valid structure, semicolons would not be inserted. For example:
```js-nolint example-bad
const a = 1
(1).toString()
const b = 1
[1, 2, 3].forEach(console.log)
```
Because `()` can be seen as a function call, it would usually not trigger ASI. Similarly, `[]` may be a member access. The code above is equivalent to:
```js-nolint example-bad
const a = 1(1).toString();
const b = 1[1, 2, 3].forEach(console.log);
```
This happens to be valid syntax. `1[1, 2, 3]` is a [property accessor](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors) with a [comma](/en-US/docs/Web/JavaScript/Reference/Operators/Comma_operator)-joined expression. Therefore, you would get errors like "1 is not a function" and "Cannot read properties of undefined (reading 'forEach')" when running the code.
Within classes, class fields and generator methods can be a pitfall as well.
```js-nolint example-bad
class A {
a = 1
*gen() {}
}
```
It is seen as:
```js-nolint example-bad
class A {
a = 1 * gen() {}
}
```
And therefore will be a syntax error around `{`.
There are the following rules-of-thumb for dealing with ASI, if you want to enforce semicolon-less style:
- Write postfix `++` and `--` on the same line as their operands.
```js-nolint example-bad
const a = b
++
console.log(a) // ReferenceError: Invalid left-hand side expression in prefix operation
```
```js-nolint example-good
const a = b++
console.log(a)
```
- The expressions after `return`, `throw`, or `yield` should be on the same line as the keyword.
```js-nolint example-bad
function foo() {
return
1 + 1 // Returns undefined; 1 + 1 is ignored
}
```
```js-nolint example-good
function foo() {
return 1 + 1
}
function foo() {
return (
1 + 1
)
}
```
- Similarly, the label identifier after `break` or `continue` should be on the same line as the keyword.
```js-nolint example-bad
outerBlock: {
innerBlock: {
break
outerBlock // SyntaxError: Illegal break statement
}
}
```
```js-nolint example-good
outerBlock: {
innerBlock: {
break outerBlock
}
}
```
- The `=>` of an arrow function should be on the same line as the end of its parameters.
```js-nolint example-bad
const foo = (a, b)
=> a + b
```
```js-nolint example-good
const foo = (a, b) =>
a + b
```
- The `async` of async functions, methods, etc. cannot be directly followed by a line terminator.
```js-nolint example-bad
async
function foo() {}
```
```js-nolint example-good
async function
foo() {}
```
- If a line starts with one of `(`, `[`, `` ` ``, `+`, `-`, `/` (as in regex literals), prefix it with a semicolon, or end the previous line with a semicolon.
```js-nolint example-bad
// The () may be merged with the previous line as a function call
(() => {
// ...
})()
// The [ may be merged with the previous line as a property access
[1, 2, 3].forEach(console.log)
// The ` may be merged with the previous line as a tagged template literal
`string text ${data}`.match(pattern).forEach(console.log)
// The + may be merged with the previous line as a binary + expression
+a.toString()
// The - may be merged with the previous line as a binary - expression
-a.toString()
// The / may be merged with the previous line as a division expression
/pattern/.exec(str).forEach(console.log)
```
```js-nolint example-good
;(() => {
// ...
})()
;[1, 2, 3].forEach(console.log)
;`string text ${data}`.match(pattern).forEach(console.log)
;+a.toString()
;-a.toString()
;/pattern/.exec(str).forEach(console.log)
```
- Class fields should preferably always be ended with semicolons β in addition to the previous rule (which includes a field declaration followed by a [computed property](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names), since the latter starts with `[`), semicolons are also required between a field declaration and a generator method.
```js-nolint example-bad
class A {
a = 1
[b] = 2
*gen() {} // Seen as a = 1[b] = 2 * gen() {}
}
```
```js-nolint example-good
class A {
a = 1;
[b] = 2;
*gen() {}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Grammar and types](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types) guide
- [Micro-feature from ES6, now in Firefox Aurora and Nightly: binary and octal numbers](https://whereswalden.com/2013/08/12/micro-feature-from-es6-now-in-firefox-aurora-and-nightly-binary-and-octal-numbers/) by Jeff Walden (2013)
- [JavaScript character escape sequences](https://mathiasbynens.be/notes/javascript-escapes) by Mathias Bynens (2011)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference | data/mdn-content/files/en-us/web/javascript/reference/regular_expressions/index.md | ---
title: Regular expressions
slug: Web/JavaScript/Reference/Regular_expressions
page-type: landing-page
browser-compat: javascript.regular_expressions
---
{{jsSidebar}}
A **regular expression** (_regex_ for short) allow developers to match strings against a pattern, extract submatch information, or simply test if the string conforms to that pattern. Regular expressions are used in many programming languages, and JavaScript's syntax is inspired by [Perl](https://www.perl.org/).
You are encouraged to read the [regular expressions guide](/en-US/docs/Web/JavaScript/Guide/Regular_expressions) to get an overview of the available regex syntaxes and how they work.
## Description
[_Regular expressions_](https://en.wikipedia.org/wiki/Regular_expression) are a important concept in formal language theory. They are a way to describe a possibly infinite set of character strings (called a _language_). A regular expression, at its core, needs the following features:
- A set of _characters_ that can be used in the language, called the _alphabet_.
- _Concatenation_: `ab` means "the character `a` followed by the character `b`".
- _Union_: `a|b` means "either `a` or `b`".
- _Kleene star_: `a*` means "zero or more `a` characters".
Assuming a finite alphabet (such as the 26 letters of the English alphabet, or the entire Unicode character set), all regular languages can be generated by the features above. Of course, many patterns are very tedious to express this way (such as "10 digits" or "a character that's not a space"), so JavaScript regular expressions include many shorthands, introduced below.
> **Note:** JavaScript regular expressions are in fact not regular, due to the existence of [backreferences](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Backreference) (regular expressions must have finite states). However, they are still a very useful feature.
### Creating regular expressions
A regular expression is typically created as a literal by enclosing a pattern in forward slashes (`/`):
```js
const regex1 = /ab+c/g;
```
Regular expressions can also be created with the {{jsxref("RegExp/RegExp", "RegExp()")}} constructor:
```js
const regex2 = new RegExp("ab+c", "g");
```
They have no runtime differences, although they may have implications on performance, static analyzability, and authoring ergonomic issues with escaping characters. For more information, see the [`RegExp`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#literal_notation_and_constructor) reference.
### Regex flags
Flags are special parameters that can change the way a regular expression is interpreted or the way it interacts with the input text. Each flag corresponds to one accessor property on the `RegExp` object.
| Flag | Description | Corresponding property |
| ---- | --------------------------------------------------------------------------------------------- | ----------------------------------------------- |
| `d` | Generate indices for substring matches. | {{jsxref("RegExp/hasIndices", "hasIndices")}} |
| `g` | Global search. | {{jsxref("RegExp/global", "global")}} |
| `i` | Case-insensitive search. | {{jsxref("RegExp/ignoreCase", "ignoreCase")}} |
| `m` | Allows `^` and `$` to match next to newline characters. | {{jsxref("RegExp/multiline", "multiline")}} |
| `s` | Allows `.` to match newline characters. | {{jsxref("RegExp/dotAll", "dotAll")}} |
| `u` | "Unicode"; treat a pattern as a sequence of Unicode code points. | {{jsxref("RegExp/unicode", "unicode")}} |
| `v` | An upgrade to the `u` mode with more Unicode features. | {{jsxref("RegExp/unicodeSets", "unicodeSets")}} |
| `y` | Perform a "sticky" search that matches starting at the current position in the target string. | {{jsxref("RegExp/sticky", "sticky")}} |
The sections below list all available regex syntaxes, grouped by their syntactic nature.
### Assertions
Assertions are constructs that test whether the string meets a certain condition at the specified position, but not consume characters. Assertions cannot be [quantified](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Quantifier).
- [Input boundary assertion: `^`, `$`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Input_boundary_assertion)
- : Asserts that the current position is the start or end of input, or start or end of a line if the `m` flag is set.
- [Lookahead assertion: `(?=...)`, `(?!...)`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookahead_assertion)
- : Asserts that the current position is followed or not followed by a certain pattern.
- [Lookbehind assertion: `(?<=...)`, `(?<!...)`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookbehind_assertion)
- : Asserts that the current position is preceded or not preceded by a certain pattern.
- [Word boundary assertion: `\b`, `\B`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Word_boundary_assertion)
- : Asserts that the current position is a word boundary.
### Atoms
Atoms are the most basic units of a regular expression. Each atom _consumes_ one or more characters in the string, and either fails the match or allows the pattern to continue matching with the next atom.
- [Backreference: `\1`, `\2`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Backreference)
- : Matches a previously matched subpattern captured with a capturing group.
- [Capturing group: `(...)`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Capturing_group)
- : Matches a subpattern and remembers information about the match.
- [Character class: `[...]`, `[^...]`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class)
- : Matches any character in or not in a set of characters. When the [`v`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicodeSets) flag is enabled, it can also be used to match finite-length strings.
- [Character class escape: `\d`, `\D`, `\w`, `\W`, `\s`, `\S`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class_escape)
- : Matches any character in or not in a predefined set of characters.
- [Character escape: `\n`, `\u{...}`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape)
- : Matches a character that may not be able to be conveniently represented in its literal form.
- [Literal character: `a`, `b`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Literal_character)
- : Matches a specific character.
- [Named backreference: `\k<name>`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_backreference)
- : Matches a previously matched subpattern captured with a named capturing group.
- [Named capturing group: `(?<name>...)`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_capturing_group)
- : Matches a subpattern and remembers information about the match. The group can later be identified by a custom name instead of by its index in the pattern.
- [Non-capturing group: `(?:...)`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Non-capturing_group)
- : Matches a subpattern without remembering information about the match.
- [Unicode character class escape: `\p{...}`, `\P{...}`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape)
- : Matches a set of characters specified by a Unicode property. When the [`v`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicodeSets) flag is enabled, it can also be used to match finite-length strings.
- [Wildcard: `.`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Wildcard)
- : Matches any character except line terminators, unless the `s` flag is set.
### Other features
These features do not specify any pattern themselves, but are used to compose patterns.
- [Disjunction: `|`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Disjunction)
- : Matches any of a set of alternatives separated by the `|` character.
- [Quantifier: `*`, `+`, `?`, `{n}`, `{n,}`, `{n,m}`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Quantifier)
- : Matches an atom a certain number of times.
### Escape sequences
_Escape sequences_ in regexes refer to any kind of syntax formed by `\` followed by one or more characters. They may serve very different purposes depending on what follow `\`. Below is a list of all valid "escape sequences":
| Escape sequence | Followed by | Meaning |
| --------------- | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `\B` | None | [Non-word-boundary assertion][WBA] |
| `\D` | None | [Character class escape][CCE] representing non-digit characters |
| `\P` | `{`, a Unicode property and/or value, then `}` | [Unicode character class escape][UCCE] representing characters without the specified Unicode property |
| `\S` | None | [Character class escape][CCE] representing non-white-space characters |
| `\W` | None | [Character class escape][CCE] representing non-word characters |
| `\b` | None | [Word boundary assertion][WBA]; inside [character classes][CC], represents U+0008 (BACKSPACE) |
| `\c` | A letter from `A` to `Z` or `a` to `z` | A [character escape][CE] representing the control character with value equal to the letter's character value modulo 32 |
| `\d` | None | [Character class escape][CCE] representing digit characters (`0` to `9`) |
| `\f` | None | [Character escape][CE] representing U+000C (FORM FEED) |
| `\k` | `<`, an identifier, then `>` | A [named backreference][NBR] |
| `\n` | None | [Character escape][CE] representing U+000A (LINE FEED) |
| `\p` | `{`, a Unicode property and/or value, then `}` | [Unicode character class escape][UCCE] representing characters with the specified Unicode property |
| `\q` | `{`, a string, then a `}` | Only valid inside [`v`-mode character classes][VCC]; represents the string to be matched literally |
| `\r` | None | [Character escape][CE] representing U+000D (CARRIAGE RETURN) |
| `\s` | None | [Character class escape][CCE] representing whitespace characters |
| `\t` | None | [Character escape][CE] representing U+0009 (CHARACTER TABULATION) |
| `\u` | 4 hexadecimal digits; or `{`, 1 to 6 hexadecimal digits, then `}` | [Character escape][CE] representing the character with the given code point |
| `\v` | None | [Character escape][CE] representing U+000B (LINE TABULATION) |
| `\w` | None | [Character class escape][CCE] representing word characters (`A` to `Z`, `a` to `z`, `0` to `9`, `_`) |
| `\x` | 2 hexadecimal digits | [Character escape][CE] representing the character with the given value |
| `\0` | None | [Character escape][CE] representing U+0000 (NULL) |
[CC]: /en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class
[CCE]: /en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class_escape
[CE]: /en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape
[NBR]: /en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_backreference
[UCCE]: /en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape
[VCC]: /en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class#v-mode_character_class
[WBA]: /en-US/docs/Web/JavaScript/Reference/Regular_expressions/Word_boundary_assertion
`\` followed by any other digit character becomes a [legacy octal escape sequence](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#escape_sequences), which is forbidden in [Unicode-aware mode](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode).
In addition, `\` can be followed by some non-letter-or-digit characters, in which case the escape sequence is always a [character escape](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape) representing the escaped character itself:
- `\$`, `\(`, `\)`, `\*`, `\+`, `\.`, `\/`, `\?`, `\[`, `\\`, `\]`, `\^`, `\{`, `\|`, `\}`: valid everywhere
- `\-`: only valid inside [character classes](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class)
- `\!`, `\#`, `\%`, `\&`, `\,`, `\:`, `\;`, `\<`, `\=`, `\>`, `\@`, `` \` ``, `\~`: only valid inside [`v`-mode character classes](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class#v-mode_character_class)
The other {{Glossary("ASCII")}} characters, namely space character, `"`, `'`, `_`, and any letter character not mentioned above, are not valid escape sequences. In [Unicode-unaware mode](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode), escape sequences that are not one of the above become _identity escapes_: they represent the character that follows the backslash. For example, `\a` represents the character `a`. This behavior limits the ability to introduce new escape sequences without causing backward compatibility issues, and is therefore forbidden in Unicode-aware mode.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Regular expressions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions) guide
- {{jsxref("RegExp")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/regular_expressions | data/mdn-content/files/en-us/web/javascript/reference/regular_expressions/wildcard/index.md | ---
title: "Wildcard: ."
slug: Web/JavaScript/Reference/Regular_expressions/Wildcard
page-type: javascript-language-feature
browser-compat: javascript.regular_expressions.wildcard
---
{{jsSidebar}}
A **wildcard** matches all characters except line terminators. It also matches line terminators if the `s` flag is set.
## Syntax
```regex
.
```
## Description
`.` matches any character except [line terminators](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators). If the [`s`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/dotAll) flag is set, `.` also matches line terminators.
The exact character set matched by `.` depends on whether the regex is [Unicode-aware](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode). If it is Unicode-aware, `.` matches any Unicode code point; otherwise, it matches any UTF-16 code unit. For example:
```js
/../.test("π"); // true; matches two UTF-16 code units as a surrogate pair
/../u.test("π"); // false; input only has one Unicode character
```
## Examples
### Usage with quantifiers
Wildcards are often used with [quantifiers](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Quantifier) to match any character sequence, until the next character of interest is found. For example, the following example extracts the title of a Markdown page in the form `# Title`:
```js
function parseTitle(entry) {
// Use multiline mode because the title may not be at the start of
// the file. Note that the m flag does not make . match line
// terminators, so the title must be on a single line
// Return text matched by the first capturing group.
return /^#[ \t]+(.+)$/m.exec(entry)?.[1];
}
parseTitle("# Hello world"); // "Hello world"
parseTitle("## Subsection"); // undefined
parseTitle(`
---
slug: Web/JavaScript/Reference/Regular_expressions/Wildcard
---
# Wildcard: .
A **wildcard** matches all characters except line terminators.
`); // "Wildcard: ."
```
### Matching code block content
The following example matches the content of a code block enclosed by three backticks in Markdown. It uses the `s` flag to make `.` match line terminators, because the content of a code block may span multiple lines:
````js
function parseCodeBlock(entry) {
return /^```.*?^(.+?)\n```/ms.exec(entry)?.[1];
}
parseCodeBlock(`
\`\`\`js
console.log("Hello world");
\`\`\`
`); // "console.log("Hello world");"
parseCodeBlock(`
A \`try...catch\` statement must have the blocks enclosed in curly braces.
\`\`\`js example-bad
try
doSomething();
catch (e)
console.log(e);
\`\`\`
`); // "try\n doSomething();\ncatch (e)\n console.log(e);"
````
> **Warning:** These examples are for demonstration only. If you want to parse Markdown, use a dedicated Markdown parser because there are many edge cases to consider.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Character classes](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes) guide
- [Regular expressions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions)
- [Character class: `[...]`, `[^...]`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class)
- [Character class escape: `\d`, `\D`, `\w`, `\W`, `\s`, `\S`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class_escape)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/regular_expressions | data/mdn-content/files/en-us/web/javascript/reference/regular_expressions/unicode_character_class_escape/index.md | ---
title: "Unicode character class escape: \\p{...}, \\P{...}"
slug: Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape
page-type: javascript-language-feature
browser-compat: javascript.regular_expressions.unicode_character_class_escape
---
{{jsSidebar}}
A **unicode character class escape** is a kind of [character class escape](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class_escape) that matches a set of characters specified by a Unicode property. It's only supported in [Unicode-aware mode](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode). When the [`v`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicodeSets) flag is enabled, it can also be used to match finite-length strings.
{{EmbedInteractiveExample("pages/js/regexp-unicode-property-escapes.html", "taller")}}
## Syntax
```regex
\p{loneProperty}
\P{loneProperty}
\p{property=value}
\P{property=value}
```
### Parameters
- `loneProperty`
- : A lone Unicode property name or value, following the same syntax as `value`. It specifies the value for the `General_Category` property, or a [binary property name](https://tc39.es/ecma262/multipage/text-processing.html#table-binary-unicode-properties). In [`v`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicodeSets) mode, it can also be a [binary Unicode property of strings](https://tc39.es/ecma262/multipage/text-processing.html#table-binary-unicode-properties-of-strings).
> **Note:** [ICU](https://unicode-org.github.io/icu/userguide/strings/unicodeset.html#property-values) syntax allows omitting the `Script` property name as well, but JavaScript does not support this, because most of the time `Script_Extensions` is more useful than `Script`.
- `property`
- : A Unicode property name. Must be made of {{Glossary("ASCII")}} letters (`AβZ`, `aβz`) and underscores (`_`), and must be one of the [non-binary property names](https://tc39.es/ecma262/multipage/text-processing.html#table-nonbinary-unicode-properties).
- `value`
- : A Unicode property value. Must be made of ASCII letters (`AβZ`, `aβz`), underscores (`_`), and digits (`0β9`), and must be one of the supported values listed in [`PropertyValueAliases.txt`](https://unicode.org/Public/UCD/latest/ucd/PropertyValueAliases.txt).
## Description
`\p` and `\P` are only supported in [Unicode-aware mode](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode). In Unicode-unaware mode, they are [identity escapes](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape) for the `p` or `P` character.
Every Unicode character has a set of properties that describe it. For example, the character [`a`](https://util.unicode.org/UnicodeJsps/character.jsp?a=0061) has the `General_Category` property with value `Lowercase_Letter`, and the `Script` property with value `Latn`. The `\p` and `\P` escape sequences allow you to match a character based on its properties. For example, `a` can be matched by `\p{Lowercase_Letter}` (the `General_Category` property name is optional) as well as `\p{Script=Latn}`. `\P` creates a _complement class_ that consists of code points without the specified property.
To compose multiple properties, use the [character set intersection](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class#v-mode_character_class) syntax enabled with the `v` flag, or see [pattern subtraction and intersection](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookahead_assertion#pattern_subtraction_and_intersection).
In `v` mode, `\p` may match a sequence of code points, defined in Unicode as "properties of strings". This is most useful for emojis, which are often composed of multiple code points. However, `\P` can only complement character properties.
> **Note:** There are plans to port the properties of strings feature to `u` mode as well.
## Examples
### General categories
General categories are used to classify Unicode characters and subcategories are available to define a more precise categorization. It is possible to use both short or long forms in Unicode property escapes.
They can be used to match letters, numbers, symbols, punctuations, spaces, etc. For a more exhaustive list of general categories, please refer to [the Unicode specification](https://unicode.org/reports/tr18/#General_Category_Property).
```js
// finding all the letters of a text
const story = "It's the Cheshire Cat: now I shall have somebody to talk to.";
// Most explicit form
story.match(/\p{General_Category=Letter}/gu);
// It is not mandatory to use the property name for General categories
story.match(/\p{Letter}/gu);
// This is equivalent (short alias):
story.match(/\p{L}/gu);
// This is also equivalent (conjunction of all the subcategories using short aliases)
story.match(/\p{Lu}|\p{Ll}|\p{Lt}|\p{Lm}|\p{Lo}/gu);
```
### Scripts and script extensions
Some languages use different scripts for their writing system. For instance, English and Spanish are written using the Latin script while Arabic and Russian are written with other scripts (respectively Arabic and Cyrillic). The `Script` and `Script_Extensions` Unicode properties allow regular expression to match characters according to the script they are mainly used with (`Script`) or according to the set of scripts they belong to (`Script_Extensions`).
For example, `A` belongs to the `Latin` script and `Ξ΅` to the `Greek` script.
```js
const mixedCharacters = "aΞ΅Π";
// Using the canonical "long" name of the script
mixedCharacters.match(/\p{Script=Latin}/u); // a
// Using a short alias (ISO 15924 code) for the script
mixedCharacters.match(/\p{Script=Grek}/u); // Ξ΅
// Using the short name sc for the Script property
mixedCharacters.match(/\p{sc=Cyrillic}/u); // Π
```
For more details, refer to [the Unicode specification](https://unicode.org/reports/tr24/#Script), the [Scripts table in the ECMAScript specification](https://tc39.es/ecma262/multipage/text-processing.html#table-unicode-script-values), and the [ISO 15924 list of script codes](https://unicode.org/iso15924/iso15924-codes.html).
If a character is used in a limited set of scripts, the `Script` property will only match for the "predominant" used script. If we want to match characters based on a "non-predominant" script, we could use the `Script_Extensions` property (`Scx` for short).
```js
// Ω’ is the digit 2 in Arabic-Indic notation
// while it is predominantly written within the Arabic script
// it can also be written in the Thaana script
"Ω’".match(/\p{Script=Thaana}/u);
// null as Thaana is not the predominant script
"Ω’".match(/\p{Script_Extensions=Thaana}/u);
// ["Ω’", index: 0, input: "Ω’", groups: undefined]
```
### Unicode property escapes vs. character classes
With JavaScript regular expressions, it is also possible to use [character classes](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes) and especially `\w` or `\d` to match letters or digits. However, such forms only match characters from the _Latin_ script (in other words, `a` to `z` and `A` to `Z` for `\w` and `0` to `9` for `\d`). As shown in [this example](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes#looking_for_a_word_from_unicode_characters), it might be a bit clumsy to work with non Latin texts.
Unicode property escapes categories encompass much more characters and `\p{Letter}` or `\p{Number}` will work for any script.
```js
// Trying to use ranges to avoid \w limitations:
const nonEnglishText = "ΠΡΠΈΠΊΠ»ΡΡΠ΅Π½ΠΈΡ ΠΠ»ΠΈΡΡ Π² Π‘ΡΡΠ°Π½Π΅ ΡΡΠ΄Π΅Ρ";
const regexpBMPWord = /([\u0000-\u0019\u0021-\uFFFF])+/gu;
// BMP goes through U+0000 to U+FFFF but space is U+0020
console.table(nonEnglishText.match(regexpBMPWord));
// Using Unicode property escapes instead
const regexpUPE = /\p{L}+/gu;
console.table(nonEnglishText.match(regexpUPE));
```
### Matching prices
The following example matches prices in a string:
```js
function getPrices(str) {
// Sc stands for "currency symbol"
return [...str.matchAll(/\p{Sc}\s*[\d.,]+/gu)].map((match) => match[0]);
}
const str = `California rolls $6.99
Crunchy rolls $8.49
Shrimp tempura $10.99`;
console.log(getPrices(str)); // ["$6.99", "$8.49", "$10.99"]
const str2 = `US store $19.99
Europe store β¬18.99
Japan store Β₯2000`;
console.log(getPrices(str2)); // ["$19.99", "β¬18.99", "Β₯2000"]
```
### Matching strings
With the `v` flag, `\p{β¦}` can match strings that are potentially longer than one character by using a property of strings:
```js
const flag = "πΊπ³";
console.log(flag.length); // 2
console.log(/\p{RGI_Emoji_Flag_Sequence}/v.exec(flag)); // [ 'πΊπ³' ]
```
However, you can't use `\P` to match "a string that does not have a property", because it's unclear how many characters should be consumed.
```js-nolint example-bad
/\P{RGI_Emoji_Flag_Sequence}/v; // SyntaxError: Invalid regular expression: Invalid property name
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Character classes](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes) guide
- [Regular expressions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions)
- [Character class: `[...]`, `[^...]`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class)
- [Character class escape: `\d`, `\D`, `\w`, `\W`, `\s`, `\S`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class_escape)
- [Character escape: `\n`, `\u{...}`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape)
- [Disjunction: `|`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Disjunction)
- [Unicode character property](https://en.wikipedia.org/wiki/Unicode_character_property) on Wikipedia
- [ES2018: RegExp Unicode property escapes](https://2ality.com/2017/07/regexp-unicode-property-escapes.html) by Dr. Axel Rauschmayer (2017)
- [Unicode regular expressions Β§ Properties](https://unicode.org/reports/tr18/#Categories)
- [Unicode Utilities: UnicodeSet](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp)
- [RegExp v flag with set notation and properties of strings](https://v8.dev/features/regexp-v-flag) on v8.dev (2022)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/regular_expressions | data/mdn-content/files/en-us/web/javascript/reference/regular_expressions/quantifier/index.md | ---
title: "Quantifier: *, +, ?, {n}, {n,}, {n,m}"
slug: Web/JavaScript/Reference/Regular_expressions/Quantifier
page-type: javascript-language-feature
browser-compat: javascript.regular_expressions.quantifier
---
{{jsSidebar}}
A **quantifier** repeats an [atom](/en-US/docs/Web/JavaScript/Reference/Regular_expressions#atoms) a certain number of times. The quantifier is placed after the atom it applies to.
## Syntax
```regex
// Greedy
atom?
atom*
atom+
atom{count}
atom{min,}
atom{min,max}
// Non-greedy
atom??
atom*?
atom+?
atom{count}?
atom{min,}?
atom{min,max}?
```
### Parameters
- `atom`
- : A single [atom](/en-US/docs/Web/JavaScript/Reference/Regular_expressions#atoms).
- `count`
- : A non-negative integer. The number of times the atom should be repeated.
- `min`
- : A non-negative integer. The minimum number of times the atom can be repeated.
- `max` {{optional_inline}}
- : A non-negative integer. The maximum number of times the atom can be repeated. If omitted, the atom can be repeated as many times as needed.
## Description
A quantifier is placed after an [atom](/en-US/docs/Web/JavaScript/Reference/Regular_expressions#atoms) to repeat it a certain number of times. It cannot appear on its own. Each quantifier is able to specify a minimum and maximum number that a pattern must be repeated for.
| Quantifier | Minimum | Maximum |
| ----------- | ------- | -------- |
| `?` | 0 | 1 |
| `*` | 0 | Infinity |
| `+` | 1 | Infinity |
| `{count}` | `count` | `count` |
| `{min,}` | `min` | Infinity |
| `{min,max}` | `min` | `max` |
For the `{count}`, `{min,}`, and `{min,max}` syntaxes, there cannot be white spaces around the numbers β otherwise, it becomes a [literal](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Literal_character) pattern.
```js example-bad
const re = /a{1, 3}/;
re.test("aa"); // false
re.test("a{1, 3}"); // true
```
This behavior is fixed in [Unicode-aware mode](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode), where braces cannot appear literally without [escaping](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape). The ability to use `{` and `}` literally without escaping is a [deprecated syntax for web compatibility](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#regexp), and you should not rely on it.
```js-nolint example-bad
/a{1, 3}/u; // SyntaxError: Invalid regular expression: Incomplete quantifier
```
It is a syntax error if the minimum is greater than the maximum.
```js-nolint example-bad
/a{3,2}/; // SyntaxError: Invalid regular expression: numbers out of order in {} quantifier
```
Quantifiers can cause [capturing groups](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Capturing_group) to match multiple times. See the capturing groups page for more information on the behavior in this case.
Each repeated match doesn't have to be the same string.
```js
/[ab]*/.exec("aba"); // ['aba']
```
Quantifiers are _greedy_ by default, which means they try to match as many times as possible until the maximum is reached, or until it's not possible to match further. You can make a quantifier _non-greedy_ by adding a `?` after it. In this case, the quantifier will try to match as few times as possible, only matching more times if it's impossible to match the rest of the pattern with this many repetitions.
```js
/a*/.exec("aaa"); // ['aaa']; the entire input is consumed
/a*?/.exec("aaa"); // ['']; it's possible to consume no characters and still match successfully
/^a*?$/.exec("aaa"); // ['aaa']; it's not possible to consume fewer characters and still match successfully
```
However, as soon as the regex successfully matches the string at some index, it will not try subsequent indices, although that may result in fewer characters being consumed.
```js
/a*?$/.exec("aaa"); // ['aaa']; the match already succeeds at the first character, so the regex never attempts to start matching at the second character
```
Greedy quantifiers may try fewer repetitions if it's otherwise impossible to match the rest of the pattern.
```js
/[ab]+[abc]c/.exec("abbc"); // ['abbc']
```
In this example, `[ab]+` first greedily matches `"abb"`, but `[abc]c` is not able to match the rest of the pattern (`"c"`), so the quantifier is reduced to match only `"ab"`.
Greedy quantifiers avoid matching infinitely many empty strings. If the minimum number of matches is reached and no more characters are being consumed by the atom at this position, the quantifier stops matching. This is why `/(a*)*/.exec("b")` does not result in an infinite loop.
Greedy quantifiers try to match as many _times_ as possible; it does not maximize the _length_ of the match. For example, `/(aa|aabaac|ba)*/.exec("aabaac")` matches `"aa"` and then `"ba"` instead of `"aabaac"`.
Quantifiers apply to a single atom. If you want to quantify a longer pattern or a disjunction, you must [group](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Non-capturing_group) it. Quantifiers cannot be applied to [assertions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions#assertions).
```js-nolint example-bad
/^*/; // SyntaxError: Invalid regular expression: nothing to repeat
```
In [Unicode-aware mode](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode), [lookahead assertions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookahead_assertion) can be quantified. This is a [deprecated syntax for web compatibility](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#regexp), and you should not rely on it.
```js
/(?=a)?b/.test("b"); // true; the lookahead is matched 0 time
```
## Examples
### Removing HTML tags
The following example removes HTML tags enclosed in angle brackets. Note the use of `?` to avoid consuming too many characters at once.
```js
function stripTags(str) {
return str.replace(/<.+?>/g, "");
}
stripTags("<p><em>lorem</em> <strong>ipsum</strong></p>"); // 'lorem ipsum'
```
The same effect can be achieved with a greedy match, but not allowing the repeated pattern to match `>`.
```js
function stripTags(str) {
return str.replace(/<[^>]+>/g, "");
}
stripTags("<p><em>lorem</em> <strong>ipsum</strong></p>"); // 'lorem ipsum'
```
> **Warning:** This is for demonstration only β it doesn't handle `>` in attribute values. Use a proper HTML sanitizer like the [HTML sanitizer API](/en-US/docs/Web/API/HTML_Sanitizer_API) instead.
### Locating Markdown paragraphs
In Markdown, paragraphs are separated by one or more blank lines. The following example counts all paragraphs in a string by matching two or more line breaks.
```js
function countParagraphs(str) {
return str.match(/(?:\r?\n){2,}/g).length + 1;
}
countParagraphs(`
Paragraph 1
Paragraph 2
Containing some line breaks, but still the same paragraph
Another paragraph
`); // 3
```
> **Warning:** This is for demonstration only β it doesn't handle line breaks in code blocks or other Markdown block elements like headings. Use a proper Markdown parser instead.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Quantifiers](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Quantifiers) guide
- [Regular expressions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions)
- [Disjunction: `|`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Disjunction)
- [Character class: `[...]`, `[^...]`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/regular_expressions | data/mdn-content/files/en-us/web/javascript/reference/regular_expressions/character_class/index.md | ---
title: "Character class: [...], [^...]"
slug: Web/JavaScript/Reference/Regular_expressions/Character_class
page-type: javascript-language-feature
browser-compat: javascript.regular_expressions.character_class
---
{{jsSidebar}}
A **character class** matches any character in or not in a custom set of characters. When the [`v`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicodeSets) flag is enabled, it can also be used to match finite-length strings.
## Syntax
```regex
[]
[abc]
[A-Z]
[^]
[^abc]
[^A-Z]
// `v` mode only
[operand1&&operand2]
[operand1--operand2]
[\q{substring}]
```
### Parameters
- `operand1`, `operand2`
- : Can be a single character, another square-bracket-enclosed character class, a [character class escape](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class_escape), a [Unicode character class escape](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape), or a string using the `\q` syntax.
- `substring`
- : A literal string.
## Description
A character class specifies a list of characters between square brackets and matches any character in the list. The [`v`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicodeSets) flag drastically changes how character classes are parsed and interpreted. The following syntaxes are available in both `v` mode and non-`v` mode:
- A single character: matches the character itself.
- A range of characters: matches any character in the inclusive range. The range is specified by two characters separated by a dash (`-`). The first character must be smaller in character value than the second character. The _character value_ is the Unicode code point of the character. Because Unicode code points are usually assigned to alphabets in order, `[a-z]` specifies all lowercase Latin characters, while `[Ξ±-Ο]` specifies all lowercase Greek characters. In [Unicode-unaware mode](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode), regexes are interpreted as a sequence of [BMP](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_code_points_and_grapheme_clusters) characters. Therefore, surrogate pairs in character classes represent two characters instead of one; see below for details.
- Escape sequences: `\b`, `\-`, [character class escapes](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class_escape), [Unicode character class escapes](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape), and other [character escapes](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape).
These syntaxes can occur any number of times, and the character sets they represent are unioned. For example, `/[a-zA-Z0-9]/` matches any letter or digit.
The `^` prefix in a character class creates a _complement class_. For example, `[^abc]` matches any character except `a`, `b`, or `c`. The `^` character is a literal character when it appears in the middle of a character class β for example, `[a^b]` matches the characters `a`, `^`, and `b`.
The [lexical grammar](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#regular_expression_literals) does a very rough parse of regex literals, so that it does not end the regex literal at a `/` character which appears within a character class. This means `/[/]/` is valid without needing to escape the `/`.
The boundaries of a character range must not specify more than one character, which happens if you use a [character class escape](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class_escape). For example:
```js-nolint example-bad
/[\s-9]/u; // SyntaxError: Invalid regular expression: Invalid character class
```
In [Unicode-unaware mode](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode), character ranges where one boundary is a character class makes the `-` become a literal character. This is a [deprecated syntax for web compatibility](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#regexp), and you should not rely on it.
```js
/[\s-9]/.test("-"); // true
```
In [Unicode-unaware mode](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode), regexes are interpreted as a sequence of BMP characters. Therefore, surrogate pairs in character classes represent two characters instead of one.
```js
/[π]/.test("\ud83d"); // true
/[π]/u.test("\ud83d"); // false
/[π-π]/.test("π"); // SyntaxError: Invalid regular expression: /[π-π]/: Range out of order in character class
/[π-π]/u.test("π"); // true
```
Even if the pattern [ignores case](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/ignoreCase), the case of the two ends of a range is significant in determining which characters belong to the range. For example, the pattern `/[E-F]/i` only matches `E`, `F`, `e`, and `f`, while the pattern `/[E-f]/i` matches all uppercase and lowercase {{Glossary("ASCII")}} letters (because it spans over `EβZ` and `aβf`), as well as `[`, `\`, `]`, `^`, `_`, and `` ` ``.
### Non-v-mode character class
Non-`v`-mode character classes interpret most character [literally](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Literal_character) and have less restrictions about the characters they can contain. For example, `.` is the literal dot character, not the [wildcard](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Wildcard). The only characters that cannot appear literally are `\`, `]`, and `-`.
- In character classes, most escape sequences are supported, except `\b`, `\B`, and [backreferences](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Backreference). `\b` indicates a backspace character instead of a [word boundary](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Word_boundary_assertion), while the other two cause syntax errors. To use `\` literally, escape it as `\\`.
- The `]` character indicates the end of the character class. To use it literally, escape it as `\]`.
- The dash (`-`) character, when used between two characters, indicates a range. When it appears at the start or end of a character class, it is a literal character. It's also a literal character when it's used in the boundary of a range. For example, `[a-]` matches the characters `a` and `-`, `[!--]` matches the characters `!` to `-`, and `[--9]` matches the characters `-` to `9`. You can also escape it as `\-` if you want to use it literally anywhere.
### v-mode character class
The basic idea of character classes in `v` mode remains the same: you can still use most characters literally, use `-` to denote character ranges, and use escape sequences. One of the most important features of the `v` flag is _set notation_ within character classes. As previously mentioned, normal character classes can express unions by concatenating two ranges, such as using `[A-Z0-9]` to mean "the union of the set `[A-Z]` and the set `[0-9]`". However, there's no easy way to represent other operations with character sets, such as intersection and difference.
With the `v` flag, intersection is expressed with `&&`, and subtraction with `--`. The absence of both implies union. The two operands of `&&` or `--` can be a character, character escape, character class escape, or even another character class. For example, to express "a word character that's not an underscore", you can use `[\w--_]`. You cannot mix operators on the same level. For example, `[\w&&[A-z]--_]` is a syntax error. However, because you can nest character classes, you can be explicit by writing `[\w&&[[A-z]--_]]` or `[[\w&&[A-z]]--_]` (which both mean `[A-Za-z]`). Similarly, `[AB--C]` is invalid and you need to write `[A[B--C]]` (which just means `[AB]`).
In `v` mode, the [Unicode character class escape](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape) `\p` can match finite-length strings, such as emojis. For symmetry, regular character classes can also match more than one character. To write a "string literal" in a character class, you wrap the string in `\q{...}`. The only regex syntax supported here is [disjunction](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Disjunction) β apart from this, `\q` must completely enclose literals (including escaped characters). This ensures that character classes can only match finite-length strings with finitely many possibilities.
Because the character class syntax is now more sophisticated, more characters are reserved and forbidden from appearing literally.
- In addition to `]` and `\`, the following characters must be escaped in character classes if they represent literal characters: `(`, `)`, `[`, `{`, `}`, `/`, `-`, `|`. This list is somewhat similar to the list of [syntax characters](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Literal_character), except that `^`, `$`, `*`, `+`, and `?` are not reserved inside character classes, while `/` and `-` are not reserved outside character classes (although `/` may delimit a regex literal and therefore still needs to be escaped). All these characters may also be optionally escaped in `u`-mode character classes.
- The following "double punctuator" sequences must be escaped as well (but they don't make much sense without the `v` flag anyway): `&&`, `!!`, `##`, `$$`, `%%`, `**`, `++`, `,,`, `..`, `::`, `;;`, `<<`, `==`, `>>`, `??`, `@@`, `^^`, ` `` `, `~~`. In `u` mode, some of these characters can only appear literally within character classes and cause a syntax error when escaped. In `v` mode, they must be escaped when appearing in pairs, but can be optionally escaped when appearing alone. For example, `/[\!]/u` is invalid because it's an [identity escape](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape), but both `/[\!]/v` and `/[!]/v` are valid, while `/[!!]/v` is invalid. The [literal character](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Literal_character) reference has a detailed table of which characters can appear escaped or unescaped.
Complement character classes `[^...]` cannot possibly be able to match strings longer than one character. For example, `[\q{ab|c}]` is valid and matches the string `"ab"`, but `[^\q{ab|c}]` is invalid because it's unclear how many characters should be consumed. The check is done by checking if all `\q` contain single characters and all `\p` specify character properties β for unions, all operands must be purely characters; for intersections, at least one operand must be purely characters; for subtraction, the leftmost operand must be purely characters. The check is syntactic without looking at the actual character set being specified, which means although `/[^\q{ab|c}--\q{ab}]/v` is equivalent to `/[^c]/v`, it's still rejected.
### Complement classes and case-insensitive matching
In non-`v`-mode, complement character classes `[^...]` are implemented by simply inverting the match result β that is, `[^...]` matches whenever `[...]` doesn't match, and vice versa. However, the other complement classes, such as `\P{...}` and `\W`, work by eagerly constructing the set consisting of all characters without the specified property. They seem to produce the same behavior, but are made more complex when combined with [case-insensitive](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/ignoreCase) matching.
Consider the following two regexes:
```js
const r1 = /\p{Lowercase_Letter}/iu;
const r2 = /[^\P{Lowercase_Letter}]/iu;
```
The `r2` is a double negation and seems to be equivalent with `r1`. But in fact, `r1` matches all lower- and upper-case ASCII letters, while `r2` matches none. To illustrate how it works, pretend that we are only dealing with ASCII characters, not the entire Unicode character set, and `r1` and `r2` are specified as below:
```js
const r1 = /[a-z]/iu;
const r2 = /[^A-Z]/iu;
```
Recall that case-insensitive matching happens by folding both the pattern and the input to the same case (see {{jsxref("RegExp/ignoreCase", "ignoreCase")}} for more details). For `r1`, the character class `a-z` stays the same after case folding, while both upper- and lower-case ASCII string inputs are folded to lower-case, so `r1` is able to match both `"A"` and `"a"`. For `r2`, the character class `A-Z` is folded to `a-z`; however, `^` negates the match result, so that `[^A-Z]` in effect only matches upper-case strings. However, both upper- and lower-case ASCII string inputs are still folded to lower-case, causing `r2` to match nothing.
In `v` mode, this behavior is fixed β `[^...]` also eagerly constructs the complement class instead of negating the match result. This makes `[^\P{Lowercase_Letter}]` and `\p{Lowercase_Letter}` are strictly equivalent.
## Examples
### Matching hexadecimal digits
The following function determines whether a string contains a valid hexadecimal number:
```js
function isHexadecimal(str) {
return /^[0-9A-F]+$/i.test(str);
}
isHexadecimal("2F3"); // true
isHexadecimal("beef"); // true
isHexadecimal("undefined"); // false
```
### Using intersection
The following function matches Greek letters.
```js
function greekLetters(str) {
return str.match(/[\p{Script_Extensions=Greek}&&\p{Letter}]/gv);
}
// π is U+1018A GREEK ZERO SIGN
greekLetters("ΟπP0ιΆΞ±AΞ£"); // [ 'Ο', 'Ξ±', 'Ξ£' ]
```
### Using subtraction
The following function matches all non-ASCII numbers.
```js
function nonASCIINumbers(str) {
return str.match(/[\p{Decimal_Number}--[0-9]]/gv);
}
// πΉ is U+11739 AHOM DIGIT NINE
nonASCIINumbers("π0ιΆ1ππΉa"); // [ 'π', 'πΉ' ]
```
### Matching strings
The following function matches all line terminator sequences, including the [line terminator characters](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators) and the sequence `\r\n` (CRLF).
```js
function getLineTerminators(str) {
return str.match(/[\r\n\u2028\u2029\q{\r\n}]/gv);
}
getLineTerminators(`
A poem\r
Is split\r\n
Into many
Stanzas
`); // [ '\r', '\r\n', '\n' ]
```
This example is exactly equivalent to `/(?:\r|\n|\u2028|\u2029|\r\n)/gu` or `/(?:[\r\n\u2028\u2029]|\r\n)/gu`, except shorter.
The most useful case of `\q{}` is when doing subtraction and intersection. Previously, this was possible with [multiple lookaheads](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookahead_assertion#pattern_subtraction_and_intersection). The following function matches flags that are not one of the American, Chinese, Russian, British, and French flags.
```js
function notUNSCPermanentMember(flag) {
return /^[\p{RGI_Emoji_Flag_Sequence}--\q{πΊπΈ|π¨π³|π·πΊ|π¬π§|π«π·}]$/v.test(flag);
}
notUNSCPermanentMember("πΊπΈ"); // false
notUNSCPermanentMember("π©πͺ"); // true
```
This example is mostly equivalent to `/^(?!πΊπΈ|π¨π³|π·πΊ|π¬π§|π«π·)\p{RGI_Emoji_Flag_Sequence}$/v`, except perhaps more performant.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Character classes](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes) guide
- [Regular expressions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions)
- [Character class escape: `\d`, `\D`, `\w`, `\W`, `\s`, `\S`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class_escape)
- [Unicode character class escape: `\p{...}`, `\P{...}`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape)
- [Literal character: `a`, `b`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Literal_character)
- [Character escape: `\n`, `\u{...}`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape)
- [Disjunction: `|`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Disjunction)
- [RegExp v flag with set notation and properties of strings](https://v8.dev/features/regexp-v-flag) on v8.dev (2022)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/regular_expressions | data/mdn-content/files/en-us/web/javascript/reference/regular_expressions/backreference/index.md | ---
title: "Backreference: \\1, \\2"
slug: Web/JavaScript/Reference/Regular_expressions/Backreference
page-type: javascript-language-feature
browser-compat: javascript.regular_expressions.backreference
---
{{jsSidebar}}
A **backreference** refers to the submatch of a previous [capturing group](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Capturing_group) and matches the same text as that group. For [named capturing groups](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_capturing_group), you may prefer to use the [named backreference](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_backreference) syntax.
## Syntax
```regex
\N
```
> **Note:** `N` is not a literal character.
### Parameters
- `N`
- : A positive integer referring to the number of a capturing group.
## Description
A backreference is a way to match the same text as previously matched by a capturing group. Capturing groups count from 1, so the first capturing group's result can be referenced with `\1`, the second with `\2`, and so on. `\0` is a [character escape](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape) for the NUL character.
In [case-insensitive](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/ignoreCase) matching, the backreference may match text with different casing from the original text.
```js
/(b)\1/i.test("bB"); // true
```
The backreference must refer to an existent capturing group. If the number it specifies is greater than the total number of capturing groups, a syntax error is thrown.
```js-nolint example-bad
/(a)\2/u; // SyntaxError: Invalid regular expression: Invalid escape
```
In [Unicode-unaware mode](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode), invalid backreferences become a [legacy octal escape](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#escape_sequences) sequence. This is a [deprecated syntax for web compatibility](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#regexp), and you should not rely on it.
```js
/(a)\2/.test("a\x02"); // true
```
If the referenced capturing group is unmatched (for example, because it belongs to an unmatched alternative in a [disjunction](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Disjunction)), or the group hasn't matched yet (for example, because it lies to the right of the backreference), the backreference always succeeds (as if it matches the empty string).
```js
/(?:a|(b))\1c/.test("ac"); // true
/\1(a)/.test("a"); // true
```
## Examples
### Pairing quotes
The following function matches the `title='xxx'` and `title="xxx"` patterns in a string. To ensure the quotes match, we use a backreference to refer to the first quote. Accessing the second capturing group (`[2]`) returns the string between the matching quote characters:
```js
function parseTitle(metastring) {
return metastring.match(/title=(["'])(.*?)\1/)[2];
}
parseTitle('title="foo"'); // 'foo'
parseTitle("title='foo' lang='en'"); // 'foo'
parseTitle('title="Named capturing groups\' advantages"'); // "Named capturing groups' advantages"
```
### Matching duplicate words
The following function finds duplicate words in a string (which are usually typos). Note that it uses the `\w` [character class escape](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class_escape), which only matches English letters but not any accented letters or other alphabets. If you want more generic matching, you may want to [split](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) the string by whitespace and iterate over the resulting array.
```js
function findDuplicates(text) {
return text.match(/\b(\w+)\s+\1\b/i)?.[1];
}
findDuplicates("foo foo bar"); // 'foo'
findDuplicates("foo bar foo"); // undefined
findDuplicates("Hello hello"); // 'Hello'
findDuplicates("Hello hellos"); // undefined
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Groups and backreferences](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences) guide
- [Regular expressions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions)
- [Capturing group: `(...)`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Capturing_group)
- [Named capturing group: `(?<name>...)`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_capturing_group)
- [Named backreference: `\k<name>`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_backreference)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/regular_expressions | data/mdn-content/files/en-us/web/javascript/reference/regular_expressions/capturing_group/index.md | ---
title: "Capturing group: (...)"
slug: Web/JavaScript/Reference/Regular_expressions/Capturing_group
page-type: javascript-language-feature
browser-compat: javascript.regular_expressions.capturing_group
---
{{jsSidebar}}
A **capturing group** groups a subpattern, allowing you to apply a [quantifier](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Quantifier) to the entire group or use [disjunctions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Disjunction) within it. It memorizes information about the subpattern match, so that you can refer back to it later with a [backreference](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Backreference), or access the information through the [match results](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec#return_value).
If you don't need the result of the subpattern match, use a [non-capturing group](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Non-capturing_group) instead, which improves performance and avoids refactoring hazards.
## Syntax
```regex
(pattern)
```
### Parameters
- `pattern`
- : A pattern consisting of anything you may use in a regex literal, including a [disjunction](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Disjunction).
## Description
A capturing group acts like the [grouping operator](/en-US/docs/Web/JavaScript/Reference/Operators/Grouping) in JavaScript expressions, allowing you to use a subpattern as a single [atom](/en-US/docs/Web/JavaScript/Reference/Regular_expressions#atoms).
Capturing groups are numbered by the order of their opening parentheses. The first capturing group is numbered `1`, the second `2`, and so on. [Named capturing groups](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_capturing_group) are also capturing groups and are numbered together with other (unnamed) capturing groups. The information of the capturing group's match can be accessed through:
- The return value (which is an array) of {{jsxref("RegExp.prototype.exec()")}}, {{jsxref("String.prototype.match()")}}, and {{jsxref("String.prototype.matchAll()")}}
- The `pN` parameters of the {{jsxref("String.prototype.replace()")}} and {{jsxref("String.prototype.replaceAll()")}} methods' `replacement` callback function
- [Backreferences](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Backreference) within the same pattern
> **Note:** Even in `exec()`'s result array, capturing groups are accessed by numbers `1`, `2`, etc., because the `0` element is the entire match. `\0` is not a backreference, but a [character escape](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape) for the NUL character.
Capturing groups in the regex source code correspond to their results one-to-one. If a capturing group is not matched (for example, it belongs to an unmatched alternative in a [disjunction](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Disjunction)), the corresponding result is `undefined`.
```js
/(ab)|(cd)/.exec("cd"); // ['cd', undefined, 'cd']
```
Capturing groups can be [quantified](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Quantifier). In this case, the match information corresponding to this group is the last match of the group.
```js
/([ab])+/.exec("abc"); // ['ab', 'b']; because "b" comes after "a", this result overwrites the previous one
```
Capturing groups can be used in [lookahead](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookahead_assertion) and [lookbehind](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookbehind_assertion) assertions. Because lookbehind assertions match their atoms backwards, the final match corresponding to this group is the one that appears to the _left_ end of the string. However, the indices of the match groups still correspond to their relative locations in the regex source.
```js
/c(?=(ab))/.exec("cab"); // ['c', 'ab']
/(?<=(a)(b))c/.exec("abc"); // ['c', 'a', 'b']
/(?<=([ab])+)c/.exec("abc"); // ['c', 'a']; because "a" is seen by the lookbehind after the lookbehind has seen "b"
```
Capturing groups can be nested, in which case the outer group is numbered first, then the inner group, because they are ordered by their opening parentheses. If a nested group is repeated by a quantifier, then each time the group matches, the subgroups' results are all overwritten, sometimes with `undefined`.
```js
/((a+)?(b+)?(c))*/.exec("aacbbbcac"); // ['aacbbbcac', 'ac', 'a', undefined, 'c']
```
In the example above, the outer group is matched three times:
1. Matches `"aac"`, with subgroups `"aa"`, `undefined`, and `"c"`.
2. Matches `"bbbc"`, with subgroups `undefined`, `"bbb"`, and `"c"`.
3. Matches `"ac"`, with subgroups `"a"`, `undefined`, and `"c"`.
The `"bbb"` result from the second match is not preserved, because the third match overwrites it with `undefined`.
You can get the start and end indices of each capturing group in the input string by using the [`d`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/hasIndices) flag. This creates an extra `indices` property on the array returned by `exec()`.
You can optionally specify a name to a capturing group, which helps avoid pitfalls related to group positions and indexing. See [Named capturing groups](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_capturing_group) for more information.
Parentheses have other purposes in different regex syntaxes. For example, they also enclose lookahead and lookbehind assertions. Because these syntaxes all start with `?`, and `?` is a [quantifier](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Quantifier) which normally cannot occur directly after `(`, this does not lead to ambiguities.
## Examples
### Matching date
The following example matches a date in the format `YYYY-MM-DD`:
```js
function parseDate(input) {
const parts = /^(\d{4})-(\d{2})-(\d{2})$/.exec(input);
if (!parts) {
return null;
}
return parts.slice(1).map((p) => parseInt(p, 10));
}
parseDate("2019-01-01"); // [2019, 1, 1]
parseDate("2019-06-19"); // [2019, 6, 19]
```
### Pairing quotes
The following function matches the `title='xxx'` and `title="xxx"` patterns in a string. To ensure the quotes match, we use a backreference to refer to the first quote. Accessing the second capturing group (`[2]`) returns the string between the matching quote characters:
```js
function parseTitle(metastring) {
return metastring.match(/title=(["'])(.*?)\1/)[2];
}
parseTitle('title="foo"'); // 'foo'
parseTitle("title='foo' lang='en'"); // 'foo'
parseTitle('title="Named capturing groups\' advantages"'); // "Named capturing groups' advantages"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Groups and backreferences](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences) guide
- [Regular expressions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions)
- [Non-capturing group: `(?:...)`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Non-capturing_group)
- [Named capturing group: `(?<name>...)`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_capturing_group)
- [Backreference: `\1`, `\2`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Backreference)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/regular_expressions | data/mdn-content/files/en-us/web/javascript/reference/regular_expressions/named_backreference/index.md | ---
title: "Named backreference: \\k<name>"
slug: Web/JavaScript/Reference/Regular_expressions/Named_backreference
page-type: javascript-language-feature
browser-compat: javascript.regular_expressions.named_backreference
---
{{jsSidebar}}
A **named backreference** refers to the submatch of a previous [named capturing group](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_capturing_group) and matches the same text as that group. For [unnamed capturing groups](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Capturing_group), you need to use the normal [backreference](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Backreference) syntax.
## Syntax
```regex
\k<name>
```
### Parameters
- `name`
- : The name of the group. Must be a valid [identifier](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers) and refer to an existent named capturing group.
## Description
Named backreferences are very similar to normal backreferences: it refers to the text matched by a capturing group and matches the same text. The difference is that you refer to the capturing group by name instead of by number. This makes the regular expression more readable and easier to refactor and maintain.
In [Unicode-unaware mode](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode), the sequence `\k` only starts a named backreference if the regex contains at least one named capturing group. Otherwise, it is an [identity escape](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape) and is the same as the literal character `k`. This is a [deprecated syntax for web compatibility](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#regexp), and you should not rely on it.
```js
/\k/.test("k"); // true
```
## Examples
### Pairing quotes
The following function matches the `title='xxx'` and `title="xxx"` patterns in a string. To ensure the quotes match, we use a backreference to refer to the first quote. Accessing the second capturing group (`[2]`) returns the string between the matching quote characters:
```js
function parseTitle(metastring) {
return metastring.match(/title=(?<quote>["'])(.*?)\k<quote>/)[2];
}
parseTitle('title="foo"'); // 'foo'
parseTitle("title='foo' lang='en'"); // 'foo'
parseTitle('title="Named capturing groups\' advantages"'); // "Named capturing groups' advantages"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Groups and backreferences](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences) guide
- [Regular expressions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions)
- [Capturing group: `(...)`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Capturing_group)
- [Named capturing group: `(?<name>...)`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_capturing_group)
- [Backreference: `\1`, `\2`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Backreference)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/regular_expressions | data/mdn-content/files/en-us/web/javascript/reference/regular_expressions/lookahead_assertion/index.md | ---
title: "Lookahead assertion: (?=...), (?!...)"
slug: Web/JavaScript/Reference/Regular_expressions/Lookahead_assertion
page-type: javascript-language-feature
browser-compat: javascript.regular_expressions.lookahead_assertion
---
{{jsSidebar}}
A **lookahead assertion** "looks ahead": it attempts to match the subsequent input with the given pattern, but it does not consume any of the input β if the match is successful, the current position in the input stays the same.
## Syntax
```regex
(?=pattern)
(?!pattern)
```
### Parameters
- `pattern`
- : A pattern consisting of anything you may use in a regex literal, including a [disjunction](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Disjunction).
## Description
A regular expression generally matches from left to right. This is why lookahead and [lookbehind](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookbehind_assertion) assertions are called as such β lookahead asserts what's on the right, and lookbehind asserts what's on the left.
In order for a `(?=pattern)` assertion to succeed, the `pattern` must match the text after the current position, but the current position is not changed. The `(?!pattern)` form negates the assertion β it succeeds if the `pattern` does not match at the current position.
The `pattern` can contain [capturing groups](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Capturing_group). See the capturing groups page for more information on the behavior in this case.
Unlike other regular expression operators, there's no backtracking into a lookahead β this behavior is inherited from Perl. This only matters when the `pattern` contains [capturing groups](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Capturing_group) and the pattern following the lookahead contains [backreferences](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Backreference) to those captures. For example:
```js
/(?=(a+))a*b\1/.exec("baabac"); // ['aba', 'a']
// Not ['aaba', 'a']
```
The matching of the pattern above happens as follows:
1. The lookahead `(a+)` succeeds before the first `"a"` in `"baabac"`, and `"aa"` is captured because the quantifier is greedy.
2. `a*b` matches the `"aab"` in `"baabac"` because lookaheads don't consume their matched strings.
3. `\1` does not match the following string, because that requires 2 `"a"`s, but only 1 is available. So the matcher backtracks, but it doesn't go into the lookahead, so the capturing group cannot be reduced to 1 `"a"`, and the entire match fails at this point.
4. `exec()` re-attempts matching at the next position β before the second `"a"`. This time, the lookahead matches `"a"`, and `a*b` matches `"ab"`. The backreference `\1` matches the captured `"a"`, and the match succeeds.
If the regex is able to backtrack into the lookahead and revise the choice made in there, then the match would succeed at step 3 by `(a+)` matching the first `"a"` (instead of the first two `"a"`s) and `a*b` matching `"aab"`, without even re-attempting the next input position.
Negative lookaheads can contain capturing groups as well, but backreferences only make sense within the `pattern`, because if matching continues, `pattern` would necessarily be unmatched (otherwise the assertion fails). This means outside of the `pattern`, backreferences to those capturing groups in negative lookaheads always succeed. For example:
```js
/(.*?)a(?!(a+)b\2c)\2(.*)/.exec("baaabaac"); // ['baaabaac', 'ba', undefined, 'abaac']
```
The matching of the pattern above happens as follows:
1. The `(.*?)` pattern is non-greedy, so it starts by matching nothing. However, the next character is `a`, which fails to match `"b"` in the input.
2. The `(.*?)` pattern matches `"b"` so that the `a` in the pattern matches the first `"a"` in `"baaabaac"`.
3. At this position, the lookahead succeeds to match, because if `(a+)` matches `"aa"`, then `(a+)b\2c` matches `"aabaac"`. This causes the assertion to fail, so the matcher backtracks.
4. The `(.*?)` pattern matches the `"ba"` so that the `a` in the pattern matches the second `"a"` in `"baaabaac"`.
5. At this position, the lookahead fails to match, because the remaining input does not follow the pattern "any number of `"a"`s, a `"b"`, the same number of `"a"`s, a `c`". This causes the assertion to succeed.
6. However, because nothing was matched within the assertion, the `\2` backreference has no value, so it matches the empty string. This causes the rest of the input to be consumed by the `(.*)` at the end.
Normally, assertions cannot be [quantified](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Quantifier). However, in [Unicode-unaware mode](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode), lookahead assertions can be quantified. This is a [deprecated syntax for web compatibility](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#regexp), and you should not rely on it.
```js
/(?=a)?b/.test("b"); // true; the lookahead is matched 0 time
```
## Examples
### Matching strings without consuming them
Sometimes it's useful to validate that the matched string is followed by something without returning that as the result. The following example matches a string that is followed by a comma/period, but the punctuation is not included in the result:
```js
function getFirstSubsentence(str) {
return /^.*?(?=[,.])/.exec(str)?.[0];
}
getFirstSubsentence("Hello, world!"); // "Hello"
getFirstSubsentence("Thank you."); // "Thank you"
```
A similar effect can be achieved by [capturing](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Capturing_group) the submatch you are interested in.
### Pattern subtraction and intersection
Using lookahead, you can match a string multiple times with different patterns, which allows you to express complex relationships like subtraction (is X but not Y) and intersection (is both X and Y).
The following example matches any [identifier](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers) that's not a [reserved word](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#reserved_words) (only showing three reserved words here for brevity; more reserved words can be added to this disjunction). The `[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*` syntax describes exactly the set of identifier strings in the language spec; you can read more about identifiers in [lexical grammar](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers) and the `\p` escape in [Unicode character class escape](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape).
```js
function isValidIdentifierName(str) {
const re =
/^(?!(?:break|case|catch)$)[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u;
return re.test(str);
}
isValidIdentifierName("break"); // false
isValidIdentifierName("foo"); // true
isValidIdentifierName("cases"); // true
```
The following example matches a string that's both ASCII and can be used as an identifier part:
```js
function isASCIIIDPart(char) {
return /^(?=\p{ASCII}$)\p{ID_Start}$/u.test(char);
}
isASCIIIDPart("a"); // true
isASCIIIDPart("Ξ±"); // false
isASCIIIDPart(":"); // false
```
If you are doing intersection and subtraction with finitely many characters, you may want to use the [character set intersection](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class#v-mode_character_class) syntax enabled with the `v` flag.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Assertions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Assertions) guide
- [Regular expressions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions)
- [Input boundary assertion: `^`, `$`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Input_boundary_assertion)
- [Word boundary assertion: `\b`, `\B`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Word_boundary_assertion)
- [Lookbehind assertion: `(?<=...)`, `(?<!...)`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookbehind_assertion)
- [Capturing group: `(...)`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Capturing_group)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/regular_expressions | data/mdn-content/files/en-us/web/javascript/reference/regular_expressions/input_boundary_assertion/index.md | ---
title: "Input boundary assertion: ^, $"
slug: Web/JavaScript/Reference/Regular_expressions/Input_boundary_assertion
page-type: javascript-language-feature
browser-compat: javascript.regular_expressions.input_boundary_assertion
---
{{jsSidebar}}
An **input boundary assertion** checks if the current position in the string is an input boundary. An input boundary is the start or end of the string; or, if the `m` flag is set, the start or end of a line.
## Syntax
```regex
^
$
```
## Description
`^` asserts that the current position is the start of input. `$` asserts that the current position is the end of input. Both are _assertions_, so they don't consume any characters.
More precisely, `^` asserts that the character to the left is out of bounds of the string; `$` asserts that the character to the right is out of bounds of the string. If the [`m`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/multiline) flag is set, `^` also matches if the character to the left is a [line terminator](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators) character, and `$` also matches if the character to the right is a line terminator.
Unless the `m` flag is set, the `^` and `$` assertions only make sense when placed at the boundaries of the pattern, because any other characters to the left or right of them would necessarily cause the assertion to fail.
The `y` flag doesn't change the meaning of these assertions β see also [anchored sticky flag](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky#anchored_sticky_flag).
## Examples
### Removing trailing slashes
The following example removes trailing slashes from a URL string:
```js
function removeTrailingSlash(url) {
return url.replace(/\/$/, "");
}
removeTrailingSlash("https://example.com/"); // "https://example.com"
removeTrailingSlash("https://example.com/docs/"); // "https://example.com/docs"
```
### Matching file extensions
The following example checks file types by matching the file extension, which always comes at the end of the string:
```js
function isImage(filename) {
return /\.(?:png|jpe?g|webp|avif|gif)$/i.test(filename);
}
isImage("image.png"); // true
isImage("image.jpg"); // true
isImage("image.pdf"); // false
```
### Matching entire input
Sometimes you want to make sure that your regex matches the entire input, not just a substring of the input. For example, if you are determining if a string is a valid [identifier](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers), you can add input boundary assertions to both ends of the pattern:
```js
function isValidIdentifier(str) {
return /^[$_\p{ID_Start}][$_\p{ID_Continue}]*$/u.test(str);
}
isValidIdentifier("foo"); // true
isValidIdentifier("$1"); // true
isValidIdentifier("1foo"); // false
isValidIdentifier(" foo "); // false
```
This function is useful when doing codegen (generating code using code), because you can use valid identifiers differently from other string properties, such as [dot notation](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#dot_notation) instead of [bracket notation](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#bracket_notation):
```js
const variables = ["foo", "foo:bar", " foo "];
function toAssignment(key) {
if (isValidIdentifier(key)) {
return `globalThis.${key} = undefined;`;
}
// JSON.stringify() escapes quotes and other special characters
return `globalThis[${JSON.stringify(key)}] = undefined;`;
}
const statements = variables.map(toAssignment).join("\n");
console.log(statements);
// globalThis.foo = undefined;
// globalThis["foo:bar"] = undefined;
// globalThis[" foo "] = undefined;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Assertions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Assertions) guide
- [Regular expressions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions)
- [Word boundary assertion: `\b`, `\B`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Word_boundary_assertion)
- [Lookahead assertion: `(?=...)`, `(?!...)`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookahead_assertion)
- [Lookbehind assertion: `(?<=...)`, `(?<!...)`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookbehind_assertion)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/regular_expressions | data/mdn-content/files/en-us/web/javascript/reference/regular_expressions/non-capturing_group/index.md | ---
title: "Non-capturing group: (?:...)"
slug: Web/JavaScript/Reference/Regular_expressions/Non-capturing_group
page-type: javascript-language-feature
browser-compat: javascript.regular_expressions.non_capturing_group
---
{{jsSidebar}}
A **non-capturing group** groups a subpattern, allowing you to apply a [quantifier](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Quantifier) to the entire group or use [disjunctions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Disjunction) within it. It acts like the [grouping operator](/en-US/docs/Web/JavaScript/Reference/Operators/Grouping) in JavaScript expressions, and unlike [capturing groups](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Capturing_group), it does not memorize the matched text, allowing for better performance and avoiding confusion when the pattern also contains useful capturing groups.
## Syntax
```regex
(?:pattern)
```
### Parameters
- `pattern`
- : A pattern consisting of anything you may use in a regex literal, including a [disjunction](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Disjunction).
## Examples
### Grouping a subpattern and applying a quantifier
In the following example, we test if a file path ends with `styles.css` or `styles.[a hex hash].css`. Because the entire `\.[\da-f]+` part is optional, in order to apply the `?` quantifier to it, we need to group it into a new atom. Using a non-capturing group improves performance by not creating the extra match information that we don't need.
```js
function isStylesheet(path) {
return /styles(?:\.[\da-f]+)?\.css$/.test(path);
}
isStylesheet("styles.css"); // true
isStylesheet("styles.1234.css"); // true
isStylesheet("styles.cafe.css"); // true
isStylesheet("styles.1234.min.css"); // false
```
### Grouping a disjunction
A disjunction has the lowest precedence in a regular expression. If you want to use a disjunction as a part of a bigger pattern, you must group it. You are advised to use a non-capturing group unless you rely on the matched text of the disjunction. The following example matches file extensions, using the same code as the [input boundary assertion](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Input_boundary_assertion#matching_file_extensions) article:
```js
function isImage(filename) {
return /\.(?:png|jpe?g|webp|avif|gif)$/i.test(filename);
}
isImage("image.png"); // true
isImage("image.jpg"); // true
isImage("image.pdf"); // false
```
### Avoiding refactoring hazards
Capturing groups are accessed by their position in the pattern. If you add or remove a capturing group, you must also update the positions of the other capturing groups, if you are accessing them through match results or [backreferences](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Backreference). This can be a source of bugs, especially if most groups are purely for syntactic purposes (to apply quantifiers or to group disjunctions). Using non-capturing groups avoids this problem, and allows the indices of actual capturing groups to be easily tracked.
For example, suppose we have a function that matches the `title='xxx'` pattern in a string (example taken from [capturing group](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Capturing_group#pairing_quotes)). To ensure the quotes match, we use a backreference to refer to the first quote.
```js
function parseTitle(metastring) {
return metastring.match(/title=(["'])(.*?)\1/)[2];
}
parseTitle('title="foo"'); // 'foo'
```
If we later decided to add `name='xxx'` as an alias for `title=`, we will need to group the disjunction in another group:
```js example-bad
function parseTitle(metastring) {
// Oops β the backreference and index access are now off by one!
return metastring.match(/(title|name)=(["'])(.*?)\1/)[2];
}
parseTitle('name="foo"'); // Cannot read properties of null (reading '2')
// Because \1 now refers to the "name" string, which isn't found at the end.
```
Instead of locating all places where we are referring to the capturing groups' indices and updating them one-by-one, it's better to avoid using a capturing group:
```js example-good
function parseTitle(metastring) {
// Do not capture the title|name disjunction
// because we don't use its value
return metastring.match(/(?:title|name)=(["'])(.*?)\1/)[2];
}
parseTitle('name="foo"'); // 'foo'
```
[Named capturing groups](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_capturing_group) are another way to avoid refactoring hazards. It allows capturing groups to accessed by a custom name, which is unaffected when other capturing groups are added or removed.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Groups and backreferences](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences) guide
- [Regular expressions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions)
- [Capturing group: `(...)`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Capturing_group)
- [Named capturing group: `(?<name>...)`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_capturing_group)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/regular_expressions | data/mdn-content/files/en-us/web/javascript/reference/regular_expressions/word_boundary_assertion/index.md | ---
title: "Word boundary assertion: \\b, \\B"
slug: Web/JavaScript/Reference/Regular_expressions/Word_boundary_assertion
page-type: javascript-language-feature
browser-compat: javascript.regular_expressions.word_boundary_assertion
---
{{jsSidebar}}
A **word boundary assertion** checks if the current position in the string is a word boundary. A word boundary is where the next character is a word character and the previous character is not a word character, or vice versa.
## Syntax
```regex
\b
\B
```
## Description
`\b` asserts that the current position in the string is a word boundary. `\B` negates the assertion: it asserts that the current position is not a word boundary. Both are _assertions_, so unlike other [character escapes](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape) or [character class escapes](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class_escape), `\b` and `\B` don't consume any characters.
A word character includes the following:
- Letters (AβZ, aβz), numbers (0β9), and underscore (\_).
- If the regex is [Unicode-aware](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode) and the [`i`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/ignoreCase) flag is set, other Unicode characters that get canonicalized to one of the characters above through [case folding](https://unicode.org/Public/UCD/latest/ucd/CaseFolding.txt).
Word characters are also matched by the `\w` [character class escape](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class_escape).
Out-of-bounds input positions are considered non-word characters. For example, the following are successful matches:
```js
/\ba/.exec("abc");
/c\b/.exec("abc");
/\B /.exec(" abc");
/ \B/.exec("abc ");
```
## Examples
### Detecting words
The following example detects if a string contains the word "thanks" or "thank you":
```js
function hasThanks(str) {
return /\b(thanks|thank you)\b/i.test(str);
}
hasThanks("Thanks! You helped me a lot."); // true
hasThanks("Just want to say thank you for all your work."); // true
hasThanks("Thanksgiving is around the corner."); // false
```
> **Warning:** Not all languages have clearly defined word boundaries. If you are working with languages like Chinese or Thai, where there are no whitespace separators, use a more advanced library like {{jsxref("Intl.Segmenter")}} to search for words instead.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Assertions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Assertions) guide
- [Regular expressions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions)
- [Input boundary assertion: `^`, `$`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Input_boundary_assertion)
- [Lookahead assertion: `(?=...)`, `(?!...)`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookahead_assertion)
- [Lookbehind assertion: `(?<=...)`, `(?<!...)`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookbehind_assertion)
- [Character escape: `\n`, `\u{...}`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/regular_expressions | data/mdn-content/files/en-us/web/javascript/reference/regular_expressions/disjunction/index.md | ---
title: "Disjunction: |"
slug: Web/JavaScript/Reference/Regular_expressions/Disjunction
page-type: javascript-language-feature
browser-compat: javascript.regular_expressions.disjunction
---
{{jsSidebar}}
A **disjunction** specifies multiple alternatives. Any alternative matching the input causes the entire disjunction to be matched.
## Syntax
```regex
alternative1|alternative2
alternative1|alternative2|alternative3|β¦
```
### Parameters
- `alternativeN`
- : One alternative pattern, composed of a sequence of [atoms and assertions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions#assertions). Successfully matching one alternative causes the entire disjunction to be matched.
## Description
The `|` regular expression operator separates two or more _alternatives_. The pattern first tries to match the first alternative; if it fails, it tries to match the second one, and so on. For example, the following matches `"a"` instead of `"ab"`, because the first alternative already matches successfully:
```js
/a|ab/.exec("abc"); // ['a']
```
The `|` operator has the lowest precedence in a regular expression. If you want to use a disjunction as a part of a bigger pattern, you must [group](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Non-capturing_group) it.
When a grouped disjunction has more expressions after it, the matching begins by selecting the first alternative and attempting to match the rest of the regular expression. If the rest of the regular expression fails to match, the matcher tries the next alternative instead. For example,
```js
/(?:(a)|(ab))(?:(c)|(bc))/.exec("abc"); // ['abc', 'a', undefined, undefined, 'bc']
// Not ['abc', undefined, 'ab', 'c', undefined]
```
This is because by selecting `a` in the first alternative, it's possible to select `bc` in the second alternative and result in a successful match. This process is called _backtracking_, because the matcher first goes beyond the disjunction and then comes back to it when subsequent matching fails.
Note also that any capturing parentheses inside an alternative that's not matched produce `undefined` in the resulting array.
An alternative can be empty, in which case it matches the empty string (in other words, always matches).
Alternatives are always attempted left-to-right, regardless of the direction of matching (which is reversed in a [lookbehind](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookbehind_assertion)).
## Examples
### Matching file extensions
The following example matches file extensions, using the same code as the [input boundary assertion](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Input_boundary_assertion#matching_file_extensions) article:
```js
function isImage(filename) {
return /\.(?:png|jpe?g|webp|avif|gif)$/i.test(filename);
}
isImage("image.png"); // true
isImage("image.jpg"); // true
isImage("image.pdf"); // false
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Character classes](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes) guide
- [Regular expressions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions)
- [Quantifier: `*`, `+`, `?`, `{n}`, `{n,}`, `{n,m}`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Quantifier)
- [Character class: `[...]`, `[^...]`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/regular_expressions | data/mdn-content/files/en-us/web/javascript/reference/regular_expressions/character_escape/index.md | ---
title: "Character escape: \\n, \\u{...}"
slug: Web/JavaScript/Reference/Regular_expressions/Character_escape
page-type: javascript-language-feature
browser-compat: javascript.regular_expressions.character_escape
---
{{jsSidebar}}
A **character escape** represents a character that may not be able to be conveniently represented in its literal form.
## Syntax
```regex
\f, \n, \r, \t, \v
\cA, \cB, β¦, \cz
\0
\^, \$, \\, \., \*, \+, \?, \(, \), \[, \], \{, \}, \|, \/
\xHH
\uHHHH
\u{HHH}
```
> **Note:** `,` is not part of the syntax.
### Parameters
- `HHH`
- : A hexadecimal number representing the Unicode code point of the character. The `\xHH` form must have two hexadecimal digits; the `\uHHHH` form must have four; the `\u{HHH}` form may have 1 to 6 hexadecimal digits.
## Description
The following character escapes are recognized in regular expressions:
- `\f`, `\n`, `\r`, `\t`, `\v`
- : Same as those in [string literals](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#escape_sequences), except `\b`, which represents a [word boundary](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Word_boundary_assertion) in regexes unless in a [character class](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class).
- `\c` followed by a letter from `A` to `Z` or `a` to `z`
- : Represents the control character with value equal to the letter's character value modulo 32. For example, `\cJ` represents line break (`\n`), because the code point of `J` is 74, and 74 modulo 32 is 10, which is the code point of line break. Because an uppercase letter and its lowercase form differ by 32, `\cJ` and `\cj` are equivalent. You can represent control characters from 1 to 26 in this form.
- `\0`
- : Represents the U+0000 NUL character. Cannot be followed by a digit (which makes it a [legacy octal escape](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#escape_sequences) sequence).
- `\^`, `\$`, `\\`, `\.` `\*`, `\+`, `\?`, `\(`, `\)`, `\[`, `\]`, `\{`, `\}`, `\|`, `\/`
- : Represents the character itself. For example, `\\` represents a backslash, and `\(` represents a left parenthesis. These are [syntax characters](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Literal_character) in regexes (`/` is the delimiter of a regex literal), so they require escaping unless in a [character class](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class).
- `\xHH`
- : Represents the character with the given hexadecimal Unicode code point. The hexadecimal number must be exactly two digits long.
- `\uHHHH`
- : Represents the character with the given hexadecimal Unicode code point. The hexadecimal number must be exactly four digits long. Two such escape sequences can be used to represent a surrogate pair in [Unicode-aware mode](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode). (In Unicode-unaware mode, they are always two separate characters.)
- `\u{HHH}`
- : ([Unicode-aware mode](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode) only) Represents the character with the given hexadecimal Unicode code point. The hexadecimal number can be from 1 to 6 digits long.
In [Unicode-unaware mode](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode), escape sequences that are not one of the above become _identity escapes_: they represent the character that follows the backslash. For example, `\a` represents the character `a`. This behavior limits the ability to introduce new escape sequences without causing backward compatibility issues, and is therefore forbidden in Unicode-aware mode.
In Unicode-unaware mode, `]`, `{`, and `}` may appear [literally](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Literal_character) if it's not possible to parse them as the end of a character class or quantifier delimiters. This is a [deprecated syntax for web compatibility](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#regexp), and you should not rely on it.
In Unicode-unaware mode, escape sequences within [character classes](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class) of the form `\cX` where `X` is a number or `_` are decoded in the same way as those with {{Glossary("ASCII")}} letters: `\c0` is the same as `\cP` when taken modulo 32. In addition, if the form `\cX` is encountered anywhere where `X` is not one of the recognized characters, then the backslash is treated as a literal character. These syntaxes are also deprecated.
```js
/[\c0]/.test("\x10"); // true
/[\c_]/.test("\x1f"); // true
/[\c*]/.test("\\"); // true
/\c/.test("\\c"); // true
/\c0/.test("\\c0"); // true (the \c0 syntax is only supported in character classes)
```
## Examples
### Using character escapes
Character escapes are useful when you want to match a character that is not easily represented in its literal form. For example, you cannot use a line break literally in a regex literal, so you must use a character escape:
```js
const pattern = /a\nb/;
const string = `a
b`;
console.log(pattern.test(string)); // true
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Character classes](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes) guide
- [Regular expressions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions)
- [Character class: `[...]`, `[^...]`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class)
- [Character class escape: `\d`, `\D`, `\w`, `\W`, `\s`, `\S`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class_escape)
- [Literal character: `a`, `b`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Literal_character)
- [Unicode character class escape: `\p{...}`, `\P{...}`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape)
- [Backreference: `\1`, `\2`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Backreference)
- [Named backreference: `\k<name>`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_backreference)
- [Word boundary assertion: `\b`, `\B`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Word_boundary_assertion)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/regular_expressions | data/mdn-content/files/en-us/web/javascript/reference/regular_expressions/character_class_escape/index.md | ---
title: "Character class escape: \\d, \\D, \\w, \\W, \\s, \\S"
slug: Web/JavaScript/Reference/Regular_expressions/Character_class_escape
page-type: javascript-language-feature
browser-compat: javascript.regular_expressions.character_class_escape
---
{{jsSidebar}}
A **character class escape** is an escape sequence that represents a set of characters.
## Syntax
```regex
\d, \D
\s, \S
\w, \W
```
> **Note:** `,` is not part of the syntax.
## Description
Unlike [character escapes](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape), character class escapes represent a predefined _set_ of characters, much like a [character class](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class). The following character classes are supported:
- `\d`
- : Matches any digit character. Equivalent to `[0-9]`.
- `\w`
- : Matches any word character, where a word character includes letters (AβZ, aβz), numbers (0β9), and underscore (\_). If the regex is [Unicode-aware](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode) and the [`i`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/ignoreCase) flag is set, it also matches other Unicode characters that get canonicalized to one of the characters above through [case folding](https://unicode.org/Public/UCD/latest/ucd/CaseFolding.txt).
- `\s`
- : Matches any [whitespace](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#white_space) or [line terminator](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators) character.
The uppercase forms `\D`, `\W`, and `\S` create complement character classes for `\d`, `\w`, and `\s`, respectively. They match any character that is not in the set of characters matched by the lowercase form.
[Unicode character class escapes](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape) start with `\p` and `\P`, but they are only supported in [Unicode-aware mode](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode). In Unicode-unaware mode, they are [identity escapes](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape) for the `p` or `P` character.
Character class escapes can be used in [character classes](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class). However, they cannot be used as boundaries of character ranges, which is only allowed as a [deprecated syntax for web compatibility](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#regexp), and you should not rely on it.
## Examples
### Splitting by whitespace
The following example splits a string into an array of words, supporting all kinds of whitespace separators:
```js
function splitWords(str) {
return str.split(/\s+/);
}
splitWords(`Look at the stars
Look how they\tshine for you`);
// ['Look', 'at', 'the', 'stars', 'Look', 'how', 'they', 'shine', 'for', 'you']
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Character classes](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes) guide
- [Regular expressions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions)
- [Character class: `[...]`, `[^...]`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class)
- [Unicode character class escape: `\p{...}`, `\P{...}`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape)
- [Character escape: `\n`, `\u{...}`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape)
- [Disjunction: `|`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Disjunction)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/regular_expressions | data/mdn-content/files/en-us/web/javascript/reference/regular_expressions/literal_character/index.md | ---
title: "Literal character: a, b"
slug: Web/JavaScript/Reference/Regular_expressions/Literal_character
page-type: javascript-language-feature
browser-compat: javascript.regular_expressions.literal_character
---
{{jsSidebar}}
A **literal character** specifies exactly itself to be matched in the input text.
## Syntax
```regex
c
```
### Parameters
- `c`
- : A single character that is not one of the syntax characters described below.
## Description
In regular expressions, most characters can appear literally. They are usually the most basic building blocks of patterns. For example, here is a pattern from the [Removing HTML tags](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Quantifier#removing_html_tags) example:
```js
const pattern = /<.+?>/g;
```
In this example, `.`, `+`, and `?` are called _syntax characters_. They have special meanings in regular expressions. The rest of the characters in the pattern (`<` and `>`) are literal characters. They match themselves in the input text: the left and right angle brackets.
The following characters are syntax characters in regular expressions, and they cannot appear as literal characters:
- [`^`, `$`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Input_boundary_assertion)
- [`\`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape)
- [`*`, `+`, `?`, `{`, `}`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Quantifier)
- [`(`, `)`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Capturing_group)
- [`[`, `]`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class)
- [`|`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Disjunction)
Within character classes, more characters can appear literally. For more information, see the [Character class](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class) page. For example `\.` and `[.]` both match a literal `.`. In [`v`-mode character classes](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class#v-mode_character_class), however, there are a different set of characters reserved as syntax characters. To be most comprehensive, below is a table of ASCII characters and whether they may appear escaped or unescaped in different contexts, where "β
" means the character represents itself, "β" means it throws a syntax error, and "β οΈ" means the character is valid but means something other than itself.
<table class="fullwidth-table">
<thead>
<tr>
<th scope="col" rowspan="2">Characters</th>
<th scope="col" colspan="2">Outside character classes in <code>u</code> or <code>v</code> mode</th>
<th scope="col" colspan="2">In <code>u</code>-mode character classes</th>
<th scope="col" colspan="2">In <code>v</code>-mode character classes</th>
</tr>
<tr>
<th scope="col">Unescaped</th>
<th scope="col">Escaped</th>
<th scope="col">Unescaped</th>
<th scope="col">Escaped</th>
<th scope="col">Unescaped</th>
<th scope="col">Escaped</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>123456789 "'<br>ACEFGHIJKLMN<br>OPQRTUVXYZ_<br>aceghijklmop<br>quxyz</code></td>
<td>β
</td><td>β</td><td>β
</td><td>β</td><td>β
</td><td>β</td>
</tr>
<tr>
<td><code>!#%&,:;<=>@`~</code></td>
<td>β
</td><td>β</td><td>β
</td><td>β</td><td>β
</td><td>β
</td>
</tr>
<tr>
<td><code>]</code></td>
<td>β</td><td>β
</td><td>β</td><td>β
</td><td>β</td><td>β
</td>
</tr>
<tr>
<td><code>()[{}</code></td>
<td>β</td><td>β
</td><td>β
</td><td>β
</td><td>β</td><td>β
</td>
</tr>
<tr>
<td><code>*+?</code></td>
<td>β</td><td>β
</td><td>β
</td><td>β
</td><td>β
</td><td>β
</td>
</tr>
<tr>
<td><code>/</code></td>
<td>β
</td><td>β
</td><td>β
</td><td>β
</td><td>β</td><td>β
</td>
</tr>
<tr>
<td><code>0DSWbdfnrstvw</code></td>
<td>β
</td><td>β οΈ</td><td>β
</td><td>β οΈ</td><td>β
</td><td>β οΈ</td>
</tr>
<tr>
<td><code>B</code></td>
<td>β
</td><td>β οΈ</td><td>β
</td><td>β</td><td>β
</td><td>β</td>
</tr>
<tr>
<td><code>$.</code></td>
<td>β οΈ</td><td>β
</td><td>β
</td><td>β
</td><td>β
</td><td>β
</td>
</tr>
<tr>
<td><code>|</code></td>
<td>β οΈ</td><td>β
</td><td>β
</td><td>β
</td><td>β</td><td>β
</td>
</tr>
<tr>
<td><code>-</code></td>
<td>β
</td><td>β</td><td>β
β οΈ</td><td>β
</td><td>ββ οΈ</td><td>β
</td>
</tr>
<tr>
<td><code>^</code></td>
<td>β οΈ</td><td>β
</td><td>β
β οΈ</td><td>β
</td><td>β
β οΈ</td><td>β
</td>
</tr>
<tr>
<td><code>\</code></td>
<td>ββ οΈ</td><td>β
</td><td>ββ οΈ</td><td>β
</td><td>ββ οΈ</td><td>β
</td>
</tr>
</tbody>
</table>
<!--
// The table above is created with the help of this:
const tbl = {};
for (let i = 32; i < 127; i++) {
const c = String.fromCharCode(i);
const res = {};
const allChars = Array.from({ length: 127 }, (_, i) =>
String.fromCharCode(i),
);
function testProp(prop, cr) {
try {
const re = cr();
const chars = allChars.filter((c) => re.test(c));
if (chars.length !== 1 || chars[0] !== c) res[prop] = "special";
} catch {
res[prop] = "error";
}
}
testProp("outLit", () => new RegExp(`^${c}$`, "u"));
testProp("uInLit", () => new RegExp(`^[${c}]$`, "u"));
testProp("vInLit", () => new RegExp(`^[${c}]$`, "v"));
testProp("outEsc", () => new RegExp(`^\\${c}$`, "u"));
testProp("uInEsc", () => new RegExp(`^[\\${c}]$`, "u"));
testProp("vInEsc", () => new RegExp(`^[\\${c}]$`, "v"));
tbl[c] = res;
}
function groupBy(arr, cb, cb2) {
const groups = { __proto__: null };
for (const a of arr) {
const name = cb(a);
groups[name] ??= "";
groups[name] += cb2(a);
}
return groups;
}
console.log(
groupBy(
Object.entries(tbl),
(p) =>
["outLit", "outEsc", "uInLit", "uInEsc", "vInLit", "vInEsc"]
.map((k) => {
switch (p[1][k]) {
case undefined:
return "β
";
case "error":
return "β";
case "special":
return "β οΈ";
}
})
.join(""),
(p) => p[0],
),
);
-->
> **Note:** The characters that can both be escaped and unescaped in `v`-mode character classes are exactly those forbidden as "double punctuators". See [`v`-mode character classes](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class#v-mode_character_class) for more information.
Whenever you want to match a syntax character literally, you need to [escape](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape) it with a backslash (`\`). For example, to match a literal `*` in a pattern, you need to write `\*` in the pattern. Using syntax characters as literal characters either leads to unexpected results or causes syntax errors β for example, `/*/` is not a valid regular expression because the quantifier is not preceded by a pattern. In [Unicode-unaware mode](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode), `]`, `{`, and `}` may appear literally if it's not possible to parse them as the end of a character class or quantifier delimiters. This is a [deprecated syntax for web compatibility](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#regexp), and you should not rely on it.
Regular expression literals cannot be specified with certain non-syntax literal characters. `/` cannot appear as a literal character in a regular expression literal, because `/` is used as the delimiter of the literal itself. You need to escape it as `\/` if you want to match a literal `/`. Line terminators cannot appear as literal characters in a regular expression literal either, because a literal cannot span multiple lines. You need to use a [character escape](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape) like `\n` instead. There are no such restrictions when using the {{jsxref("RegExp/RegExp", "RegExp()")}} constructor, although string literals have their own escaping rules (for example, `"\\"` actually denotes a single backslash character, so `new RegExp("\\*")` and `/\*/` are equivalent).
In [Unicode-unaware mode](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/unicode#unicode-aware_mode), the pattern is interpreted as a sequence of [UTF-16 code units](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_code_points_and_grapheme_clusters). This means surrogate pairs actually represent two literal characters. This causes unexpected behaviors when paired with other features:
```js
/^[π]$/.test("π"); // false, because the pattern is interpreted as /^[\ud83d\udc04]$/
/^π+$/.test("ππ"); // false, because the pattern is interpreted as /^\ud83d\udc04+$/
```
In Unicode-aware mode, the pattern is interpreted as a sequence of Unicode code points, and surrogate pairs do not get split. Therefore, you should always prefer to use the `u` flag.
## Examples
### Using literal characters
The following example is copied from [Character escape](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape#using_character_escapes). The `a` and `b` characters are literal characters in the pattern, and `\n` is an escaped character because it cannot appear literally in a regular expression literal.
```js
const pattern = /a\nb/;
const string = `a
b`;
console.log(pattern.test(string)); // true
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Character classes](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes) guide
- [Regular expressions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions)
- [Character escape: `\n`, `\u{...}`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_escape)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/regular_expressions | data/mdn-content/files/en-us/web/javascript/reference/regular_expressions/named_capturing_group/index.md | ---
title: "Named capturing group: (?<name>...)"
slug: Web/JavaScript/Reference/Regular_expressions/Named_capturing_group
page-type: javascript-language-feature
browser-compat: javascript.regular_expressions.named_capturing_group
---
{{jsSidebar}}
A **named capturing group** is a particular kind of [capturing group](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Capturing_group) that allows to give a name to the group. The group's matching result can later be identified by this name instead of by its index in the pattern.
## Syntax
```regex
(?<name>pattern)
```
### Parameters
- `pattern`
- : A pattern consisting of anything you may use in a regex literal, including a [disjunction](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Disjunction).
- `name`
- : The name of the group. Must be a valid [identifier](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers).
## Description
Named capturing groups can be used just like capturing groups β they also have their match index in the result array, and they can be referenced through `\1`, `\2`, etc. The only difference is that they can be _additionally_ referenced by their name. The information of the capturing group's match can be accessed through:
- The `groups` property of the return value of {{jsxref("RegExp.prototype.exec()")}}, {{jsxref("String.prototype.match()")}}, and {{jsxref("String.prototype.matchAll()")}}
- The `groups` parameter of the {{jsxref("String.prototype.replace()")}} and {{jsxref("String.prototype.replaceAll()")}} methods' `replacement` callback function
- [Named backreferences](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_backreference) within the same pattern
All names must be unique within the same pattern. Multiple named capturing groups with the same name result in a syntax error.
```js-nolint example-bad
/(?<name>)(?<name>)/; // SyntaxError: Invalid regular expression: Duplicate capture group name
```
This restriction is relaxed if the duplicate named capturing groups are not in the same [disjunction alternative](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Disjunction), so for any string input, only one named capturing group can actually be matched. This is a much newer feature, so check [browser compatibility](#browser_compatibility) before using it.
```js
/(?<year>\d{4})-\d{2}|\d{2}-(?<year>\d{4})/;
// Works; "year" can either come before or after the hyphen
```
Named capturing groups will all be present in the result. If a named capturing group is not matched (for example, it belongs to an unmatched alternative in a [disjunction](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Disjunction)), the corresponding property on the `groups` object has value `undefined`.
```js
/(?<ab>ab)|(?<cd>cd)/.exec("cd").groups; // [Object: null prototype] { ab: undefined, cd: 'cd' }
```
You can get the start and end indices of each named capturing group in the input string by using the [`d`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/hasIndices) flag. In addition to accessing them on the `indices` property on the array returned by `exec()`, you can also access them by their names on `indices.groups`.
Compared to unnamed capturing groups, named capturing groups have the following advantages:
- They allow you to provide a descriptive name for each submatch result.
- They allow you to access submatch results without having to remember the order in which they appear in the pattern.
- When refactoring code, you can change the order of capturing groups without worrying about breaking other references.
## Examples
### Using named capturing groups
The following example parses a timestamp and an author name from a Git log entry (output with `git log --format=%ct,%an -- filename`):
```js
function parseLog(entry) {
const { author, timestamp } = /^(?<timestamp>\d+),(?<author>.+)$/.exec(
entry,
).groups;
return `${author} committed on ${new Date(
parseInt(timestamp) * 1000,
).toLocaleString()}`;
}
parseLog("1560979912,Caroline"); // "Caroline committed on 6/19/2019, 5:31:52 PM"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of named capturing groups in `core-js`](https://github.com/zloirock/core-js#ecmascript-string-and-regexp)
- [Groups and backreferences](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences) guide
- [Regular expressions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions)
- [Capturing group: `(...)`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Capturing_group)
- [Non-capturing group: `(?:...)`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Non-capturing_group)
- [Named backreference: `\k<name>`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Named_backreference)
- [ESLint rule: `prefer-named-capture-group`](https://eslint.org/docs/rules/prefer-named-capture-group)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/regular_expressions | data/mdn-content/files/en-us/web/javascript/reference/regular_expressions/lookbehind_assertion/index.md | ---
title: "Lookbehind assertion: (?<=...), (?<!...)"
slug: Web/JavaScript/Reference/Regular_expressions/Lookbehind_assertion
page-type: javascript-language-feature
browser-compat: javascript.regular_expressions.lookbehind_assertion
---
{{jsSidebar}}
A **lookbehind assertion** "looks behind": it attempts to match the previous input with the given pattern, but it does not consume any of the input β if the match is successful, the current position in the input stays the same. It matches each atom in its pattern in the reverse order.
## Syntax
```regex
(?<=pattern)
(?<!pattern)
```
### Parameters
- `pattern`
- : A pattern consisting of anything you may use in a regex literal, including a [disjunction](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Disjunction).
## Description
A regular expression generally matches from left to right. This is why [lookahead](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookahead_assertion) and lookbehind assertions are called as such β lookahead asserts what's on the right, and lookbehind asserts what's on the left.
In order for a `(?<=pattern)` assertion to succeed, the `pattern` must match the input immediately to the left of the current position, but the current position is not changed before matching the subsequent input. The `(?<!pattern)` form negates the assertion β it succeeds if the `pattern` does not match the input immediately to the left of the current position.
Lookbehind generally has the same semantics as lookahead β however, within a lookbehind assertion, the regular expression matches _backwards_. For example,
```js
/(?<=([ab]+)([bc]+))$/.exec("abc"); // ['', 'a', 'bc']
// Not ['', 'ab', 'c']
```
If the lookbehind matches from left to right, it should first greedily match `[ab]+`, which makes the first group capture `"ab"`, and the remaining `"c"` is captured by `[bc]+`. However, because `[bc]+` is matched first, it greedily grabs `"bc"`, leaving only `"a"` for `[ab]+`.
This behavior is reasonable β the matcher does not know where to _start_ the match (because the lookbehind may not be fixed-length), but it does know where to _end_ (at the current position). Therefore, it starts from the current position and works backwards. (Regexes in some other languages forbid non-fixed-length lookbehind to avoid this issue.)
For [quantified](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Quantifier) [capturing groups](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Capturing_group) inside the lookbehind, the match furthest to the left of the input string β instead of the one on the right β is captured because of backward matching. See the capturing groups page for more information. [Backreferences](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Backreference) inside the lookbehind must appear on the _left_ of the group it's referring to, also due to backward matching. However, [disjunctions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Disjunction) are still attempted left-to-right.
## Examples
### Matching strings without consuming them
Similar to [lookaheads](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookahead_assertion#matching_strings_without_consuming_them), lookbehinds can be used to match strings without consuming them so that only useful information is extracted. For example, the following regex matches the number in a price label:
```js
function getPrice(label) {
return /(?<=\$)\d+(?:\.\d*)?/.exec(label)?.[0];
}
getPrice("$10.53"); // "10.53"
getPrice("10.53"); // undefined
```
A similar effect can be achieved by [capturing](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Capturing_group) the submatch you are interested in.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Assertions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Assertions) guide
- [Regular expressions](/en-US/docs/Web/JavaScript/Reference/Regular_expressions)
- [Input boundary assertion: `^`, `$`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Input_boundary_assertion)
- [Word boundary assertion: `\b`, `\B`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Word_boundary_assertion)
- [Lookahead assertion: `(?=...)`, `(?!...)`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Lookahead_assertion)
- [Capturing group: `(...)`](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Capturing_group)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference | data/mdn-content/files/en-us/web/javascript/reference/operators/index.md | ---
title: Expressions and operators
slug: Web/JavaScript/Reference/Operators
page-type: landing-page
browser-compat: javascript.operators
---
{{jsSidebar("Operators")}}
This chapter documents all the JavaScript language operators, expressions and keywords.
## Expressions and operators by category
For an alphabetical listing see the sidebar on the left.
### Primary expressions
Basic keywords and general expressions in JavaScript. These expressions have the highest precedence (higher than [operators](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence)).
- {{jsxref("Operators/this", "this")}}
- : The `this` keyword refers to a special property of an execution context.
- [Literals](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#literals)
- : Basic `null`, boolean, number, and string literals.
- {{jsxref("Array", "[]")}}
- : Array initializer/literal syntax.
- {{jsxref("Operators/Object_initializer", "{}")}}
- : Object initializer/literal syntax.
- {{jsxref("Operators/function", "function")}}
- : The `function` keyword defines a function expression.
- {{jsxref("Operators/class", "class")}}
- : The `class` keyword defines a class expression.
- {{jsxref("Operators/function*", "function*")}}
- : The `function*` keyword defines a generator function expression.
- {{jsxref("Operators/async_function", "async function")}}
- : The `async function` defines an async function expression.
- {{jsxref("Operators/async_function*", "async function*")}}
- : The `async function*` keywords define an async generator function expression.
- {{jsxref("RegExp", "/ab+c/i")}}
- : Regular expression literal syntax.
- {{jsxref("Template_literals", "`string`")}}
- : Template literal syntax.
- {{jsxref("Operators/Grouping", "( )")}}
- : Grouping operator.
### Left-hand-side expressions
Left values are the destination of an assignment.
- {{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}
- : Member operators provide access to a property or method of an object (`object.property` and `object["property"]`).
- {{jsxref("Operators/Optional_chaining", "?.")}}
- : The optional chaining operator returns `undefined` instead of causing an error if a reference is [nullish](/en-US/docs/Glossary/Nullish) ([`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) or [`undefined`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined)).
- {{jsxref("Operators/new", "new")}}
- : The `new` operator creates an instance of a constructor.
- {{jsxref("Operators/new%2Etarget", "new.target")}}
- : In constructors, `new.target` refers to the constructor that was invoked by {{jsxref("Operators/new", "new")}}.
- {{jsxref("Operators/import%2Emeta", "import.meta")}}
- : An object exposing context-specific metadata to a JavaScript module.
- {{jsxref("Operators/super", "super")}}
- : The `super` keyword calls the parent constructor or allows accessing properties of the parent object.
- {{jsxref("Operators/import", "import()")}}
- : The `import()` syntax allows loading a module asynchronously and dynamically into a potentially non-module environment.
### Increment and decrement
Postfix/prefix increment and postfix/prefix decrement operators.
- {{jsxref("Operators/Increment", "A++")}}
- : Postfix increment operator.
- {{jsxref("Operators/Decrement", "A--")}}
- : Postfix decrement operator.
- {{jsxref("Operators/Increment", "++A")}}
- : Prefix increment operator.
- {{jsxref("Operators/Decrement", "--A")}}
- : Prefix decrement operator.
### Unary operators
A unary operation is an operation with only one operand.
- {{jsxref("Operators/delete", "delete")}}
- : The `delete` operator deletes a property from an object.
- {{jsxref("Operators/void", "void")}}
- : The `void` operator evaluates an expression and discards its return value.
- {{jsxref("Operators/typeof", "typeof")}}
- : The `typeof` operator determines the type of a given object.
- {{jsxref("Operators/Unary_plus", "+")}}
- : The unary plus operator converts its operand to Number type.
- {{jsxref("Operators/Unary_negation", "-")}}
- : The unary negation operator converts its operand to Number type and then negates it.
- {{jsxref("Operators/Bitwise_NOT", "~")}}
- : Bitwise NOT operator.
- {{jsxref("Operators/Logical_NOT", "!")}}
- : Logical NOT operator.
- {{jsxref("Operators/await", "await")}}
- : Pause and resume an async function and wait for the promise's fulfillment/rejection.
### Arithmetic operators
Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.
- {{jsxref("Operators/Exponentiation", "**")}}
- : Exponentiation operator.
- {{jsxref("Operators/Multiplication", "*")}}
- : Multiplication operator.
- {{jsxref("Operators/Division", "/")}}
- : Division operator.
- {{jsxref("Operators/Remainder", "%")}}
- : Remainder operator.
- {{jsxref("Operators/Addition", "+")}} (Plus)
- : Addition operator.
- {{jsxref("Operators/Subtraction", "-")}}
- : Subtraction operator.
### Relational operators
A comparison operator compares its operands and returns a boolean value based on whether the comparison is true.
- {{jsxref("Operators/Less_than", "<")}} (Less than)
- : Less than operator.
- {{jsxref("Operators/Greater_than", ">")}} (Greater than)
- : Greater than operator.
- {{jsxref("Operators/Less_than_or_equal", "<=")}}
- : Less than or equal operator.
- {{jsxref("Operators/Greater_than_or_equal", ">=")}}
- : Greater than or equal operator.
- {{jsxref("Operators/instanceof", "instanceof")}}
- : The `instanceof` operator determines whether an object is an instance of another object.
- {{jsxref("Operators/in", "in")}}
- : The `in` operator determines whether an object has a given property.
> **Note:** `=>` is not an operator, but the notation for [Arrow functions](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions).
### Equality operators
The result of evaluating an equality operator is always of type boolean based on whether the comparison is true.
- {{jsxref("Operators/Equality", "==")}}
- : Equality operator.
- {{jsxref("Operators/Inequality", "!=")}}
- : Inequality operator.
- {{jsxref("Operators/Strict_equality", "===")}}
- : Strict equality operator.
- {{jsxref("Operators/Strict_inequality", "!==")}}
- : Strict inequality operator.
### Bitwise shift operators
Operations to shift all bits of the operand.
- {{jsxref("Operators/Left_shift", "<<")}}
- : Bitwise left shift operator.
- {{jsxref("Operators/Right_shift", ">>")}}
- : Bitwise right shift operator.
- {{jsxref("Operators/Unsigned_right_shift", ">>>")}}
- : Bitwise unsigned right shift operator.
### Binary bitwise operators
Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.
- {{jsxref("Operators/Bitwise_AND", "&")}}
- : Bitwise AND.
- {{jsxref("Operators/Bitwise_OR", "|")}}
- : Bitwise OR.
- {{jsxref("Operators/Bitwise_XOR", "^")}}
- : Bitwise XOR.
### Binary logical operators
Logical operators implement boolean (logical) values and have [short-circuiting](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence#short-circuiting) behavior.
- {{jsxref("Operators/Logical_AND", "&&")}}
- : Logical AND.
- {{jsxref("Operators/Logical_OR", "||")}}
- : Logical OR.
- {{jsxref("Operators/Nullish_coalescing", "??")}}
- : Nullish Coalescing Operator.
### Conditional (ternary) operator
- {{jsxref("Operators/Conditional_operator", "(condition ? ifTrue : ifFalse)")}}
- : The conditional operator returns one of two values based on the logical value of the condition.
### Assignment operators
An assignment operator assigns a value to its left operand based on the value of its right operand.
- {{jsxref("Operators/Assignment", "=")}}
- : Assignment operator.
- {{jsxref("Operators/Multiplication_assignment", "*=")}}
- : Multiplication assignment.
- {{jsxref("Operators/Division_assignment", "/=")}}
- : Division assignment.
- {{jsxref("Operators/Remainder_assignment", "%=")}}
- : Remainder assignment.
- {{jsxref("Operators/Addition_assignment", "+=")}}
- : Addition assignment.
- {{jsxref("Operators/Subtraction_assignment", "-=")}}
- : Subtraction assignment
- {{jsxref("Operators/Left_shift_assignment", "<<=")}}
- : Left shift assignment.
- {{jsxref("Operators/Right_shift_assignment", ">>=")}}
- : Right shift assignment.
- {{jsxref("Operators/Unsigned_right_shift_assignment", ">>>=")}}
- : Unsigned right shift assignment.
- {{jsxref("Operators/Bitwise_AND_assignment", "&=")}}
- : Bitwise AND assignment.
- {{jsxref("Operators/Bitwise_XOR_assignment", "^=")}}
- : Bitwise XOR assignment.
- {{jsxref("Operators/Bitwise_OR_assignment", "|=")}}
- : Bitwise OR assignment.
- {{jsxref("Operators/Exponentiation_assignment", "**=")}}
- : Exponentiation assignment.
- {{jsxref("Operators/Logical_AND_assignment", "&&=")}}
- : Logical AND assignment.
- {{jsxref("Operators/Logical_OR_assignment", "||=")}}
- : Logical OR assignment.
- {{jsxref("Operators/Nullish_coalescing_assignment", "??=")}}
- : Nullish coalescing assignment.
- [`[a, b] = arr`, `{ a, b } = obj`](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
- : Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.
### Yield operators
- {{jsxref("Operators/yield", "yield")}}
- : Pause and resume a generator function.
- {{jsxref("Operators/yield*", "yield*")}}
- : Delegate to another generator function or iterable object.
### Spread syntax
- {{jsxref("Operators/Spread_syntax", "...obj")}}
- : Spread syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. In an object literal, the spread syntax enumerates the properties of an object and adds the key-value pairs to the object being created.
### Comma operator
- {{jsxref("Operators/Comma_operator", ",")}}
- : The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Operator precedence](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/this/index.md | ---
title: this
slug: Web/JavaScript/Reference/Operators/this
page-type: javascript-language-feature
browser-compat: javascript.operators.this
---
{{jsSidebar("Operators")}}
A function's **`this`** keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode) and non-strict mode.
In most cases, the value of `this` is determined by how a function is called (runtime {{Glossary("binding")}}). It can't be set by assignment during execution, and it may be different each time the function is called. The {{jsxref("Function.prototype.bind()")}} method can [set the value of a function's `this` regardless of how it's called](#the_bind_method), and [arrow functions](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) don't provide their own `this` binding (it retains the `this` value of the enclosing lexical context).
{{EmbedInteractiveExample("pages/js/expressions-this.html")}}
## Syntax
```js-nolint
this
```
### Value
In nonβstrict mode, `this` is always a reference to an object. In strict mode, it can be any value. For more information on how the value is determined, see the description below.
## Description
The value of `this` depends on in which context it appears: function, class, or global.
### Function context
Inside a function, the value of `this` depends on how the function is called. Think about `this` as a hidden parameter of a function β just like the parameters declared in the function definition, `this` is a binding that the language creates for you when the function body is evaluated.
For a typical function, the value of `this` is the object that the function is accessed on. In other words, if the function call is in the form `obj.f()`, then `this` refers to `obj`. For example:
```js
function getThis() {
return this;
}
const obj1 = { name: "obj1" };
const obj2 = { name: "obj2" };
obj1.getThis = getThis;
obj2.getThis = getThis;
console.log(obj1.getThis()); // { name: 'obj1', getThis: [Function: getThis] }
console.log(obj2.getThis()); // { name: 'obj2', getThis: [Function: getThis] }
```
Note how the function is the same, but based on how it's invoked, the value of `this` is different. This is analogous to how function parameters work.
The value of `this` is not the object that has the function as an own property, but the object that is used to call the function. You can prove this by calling a method of an object up in the [prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain).
```js
const obj3 = {
__proto__: obj1,
name: "obj3",
};
console.log(obj3.getThis()); // { name: 'obj3' }
```
The value of `this` always changes based on how a function is called, even when the function was defined on an object at creation:
```js
const obj4 = {
name: "obj4",
getThis() {
return this;
},
};
const obj5 = { name: "obj5" };
obj5.getThis = obj4.getThis;
console.log(obj5.getThis()); // { name: 'obj5', getThis: [Function: getThis] }
```
If the value that the method is accessed on is a primitive, `this` will be a primitive value as well β but only if the function is in strict mode.
```js
function getThisStrict() {
"use strict"; // Enter strict mode
return this;
}
// Only for demonstration β you should not mutate built-in prototypes
Number.prototype.getThisStrict = getThisStrict;
console.log(typeof (1).getThisStrict()); // "number"
```
If the function is called without being accessed on anything, `this` will be `undefined` β but only if the function is in strict mode.
```js
console.log(typeof getThisStrict()); // "undefined"
```
In non-strict mode, a special process called [`this` substitution](/en-US/docs/Web/JavaScript/Reference/Strict_mode#no_this_substitution) ensures that the value of `this` is always an object. This means:
- If a function is called with `this` set to `undefined` or `null`, `this` gets substituted with {{jsxref("globalThis")}}.
- If the function is called with `this` set to a primitive value, `this` gets substituted with the primitive value's wrapper object.
```js
function getThis() {
return this;
}
// Only for demonstration β you should not mutate built-in prototypes
Number.prototype.getThis = getThis;
console.log(typeof (1).getThis()); // "object"
console.log(getThis() === globalThis); // true
```
In typical function calls, `this` is implicitly passed like a parameter through the function's prefix (the part before the dot). You can also explicitly set the value of `this` using the {{jsxref("Function.prototype.call()")}}, {{jsxref("Function.prototype.apply()")}}, or {{jsxref("Reflect.apply()")}} methods. Using {{jsxref("Function.prototype.bind()")}}, you can create a new function with a specific value of `this` that doesn't change regardless of how the function is called. When using these methods, the `this` substitution rules above still apply if the function is non-strict.
#### Callbacks
When a function is passed as a callback, the value of `this` depends on how the callback is called, which is determined by the implementor of the API. Callbacks are _typically_ called with a `this` value of `undefined` (calling it directly without attaching it to any object), which means if the function is nonβstrict, the value of `this` is the global object ({{jsxref("globalThis")}}). This is the case for [iterative array methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), the [`Promise()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise) constructor, etc.
```js
function logThis() {
"use strict";
console.log(this);
}
[1, 2, 3].forEach(logThis); // undefined, undefined, undefined
```
Some APIs allow you to set a `this` value for invocations of the callback. For example, all iterative array methods and related ones like {{jsxref("Set.prototype.forEach()")}} accept an optional `thisArg` parameter.
```js
[1, 2, 3].forEach(logThis, { name: "obj" });
// { name: 'obj' }, { name: 'obj' }, { name: 'obj' }
```
Occasionally, a callback is called with a `this` value other than `undefined`. For example, the `reviver` parameter of {{jsxref("JSON.parse()")}} and the `replacer` parameter of {{jsxref("JSON.stringify()")}} are both called with `this` set to the object that the property being parsed/serialized belongs to.
#### Arrow functions
In [arrow functions](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), `this` retains the value of the enclosing lexical context's `this`. In other words, when evaluating an arrow function's body, the language does not create a new `this` binding.
For example, in global code, `this` is always `globalThis` regardless of strictness, because of the [global context](#global_context) binding:
```js
const globalObject = this;
const foo = () => this;
console.log(foo() === globalObject); // true
```
Arrow functions create a [closure](/en-US/docs/Web/JavaScript/Closures) over the `this` value of its surrounding scope, which means arrow functions behave as if they are "auto-bound" β no matter how it's invoked, `this` is bound to what it was when the function was created (in the example above, the global object). The same applies to arrow functions created inside other functions: their `this` remains that of the enclosing lexical context. [See example below](#this_in_arrow_functions).
Furthermore, when invoking arrow functions using `call()`, `bind()`, or `apply()`, the `thisArg` parameter is ignored. You can still pass other arguments using these methods, though.
```js
const obj = { name: "obj" };
// Attempt to set this using call
console.log(foo.call(obj) === globalObject); // true
// Attempt to set this using bind
const boundFoo = foo.bind(obj);
console.log(boundFoo() === globalObject); // true
```
#### Constructors
When a function is used as a constructor (with the {{jsxref("Operators/new", "new")}} keyword), its `this` is bound to the new object being constructed, no matter which object the constructor function is accessed on. The value of `this` becomes the value of the `new` expression unless the constructor returns another nonβprimitive value.
```js
function C() {
this.a = 37;
}
let o = new C();
console.log(o.a); // 37
function C2() {
this.a = 37;
return { a: 38 };
}
o = new C2();
console.log(o.a); // 38
```
In the second example (`C2`), because an object was returned during construction, the new object that `this` was bound to gets discarded. (This essentially makes the statement `this.a = 37;` dead code. It's not exactly dead because it gets executed, but it can be eliminated with no outside effects.)
#### super
When a function is invoked in the `super.method()` form, the `this` inside the `method` function is the same value as the `this` value around the `super.method()` call, and is generally not equal to the object that `super` refers to. This is because `super.method` is not an object member access like the ones above β it's a special syntax with different binding rules. For examples, see the [`super` reference](/en-US/docs/Web/JavaScript/Reference/Operators/super#calling_methods_from_super).
### Class context
A [class](/en-US/docs/Web/JavaScript/Reference/Classes) can be split into two contexts: static and instance. [Constructors](/en-US/docs/Web/JavaScript/Reference/Classes/constructor), methods, and instance field initializers ([public](/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields) or [private](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties)) belong to the instance context. [Static](/en-US/docs/Web/JavaScript/Reference/Classes/static) methods, static field initializers, and [static initialization blocks](/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks) belong to the static context. The `this` value is different in each context.
Class constructors are always called with `new`, so their behavior is the same as [function constructors](#constructors): the `this` value is the new instance being created. Class methods behave like methods in object literals β the `this` value is the object that the method was accessed on. If the method is not transferred to another object, `this` is generally an instance of the class.
Static methods are not properties of `this`. They are properties of the class itself. Therefore, they are generally accessed on the class, and `this` is the value of the class (or a subclass). Static initialization blocks are also evaluated with `this` set to the current class.
Field initializers are also evaluated in the context of the class. Instance fields are evaluated with `this` set to the instance being constructed. Static fields are evaluated with `this` set to the current class. This is why arrow functions in field initializers are [bound to the instance for instance fields and to the class for static fields](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#cannot_be_used_as_methods).
```js
class C {
instanceField = this;
static staticField = this;
}
const c = new C();
console.log(c.instanceField === c); // true
console.log(C.staticField === C); // true
```
#### Derived class constructors
Unlike base class constructors, derived constructors have no initial `this` binding. Calling {{jsxref("Operators/super", "super()")}} creates a `this` binding within the constructor and essentially has the effect of evaluating the following line of code, where `Base` is the base class:
```js-nolint
this = new Base();
```
> **Warning:** Referring to `this` before calling `super()` will throw an error.
Derived classes must not return before calling `super()`, unless the constructor returns an object (so the `this` value is overridden) or the class has no constructor at all.
```js
class Base {}
class Good extends Base {}
class AlsoGood extends Base {
constructor() {
return { a: 5 };
}
}
class Bad extends Base {
constructor() {}
}
new Good();
new AlsoGood();
new Bad(); // ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
```
### Global context
In the global execution context (outside of any functions or classes; may be inside [blocks](/en-US/docs/Web/JavaScript/Reference/Statements/block) or [arrow functions](#arrow_functions) defined in the global scope), the `this` value depends on what execution context the script runs in. Like [callbacks](#callbacks), the `this` value is determined by the runtime environment (the caller).
At the top level of a script, `this` refers to {{jsxref("globalThis")}} whether in strict mode or not. This is generally the same as the global object β for example, if the source is put inside an HTML [`<script>`](/en-US/docs/Web/HTML/Element/script) element and executed as a script, `this === window`.
> **Note:** `globalThis` is generally the same concept as the global object (i.e. adding properties to `globalThis` makes them global variables) β this is the case for browsers and Node β but hosts are allowed to provide a different value for `globalThis` that's unrelated to the global object.
```js
// In web browsers, the window object is also the global object:
console.log(this === window); // true
this.b = "MDN";
console.log(window.b); // "MDN"
console.log(b); // "MDN"
```
If the source is loaded as a [module](/en-US/docs/Web/JavaScript/Guide/Modules) (for HTML, this means adding `type="module"` to the `<script>` tag), `this` is always `undefined` at the top level.
If the source is executed with [`eval()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval), `this` is the same as the enclosing context for [direct eval](/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#direct_and_indirect_eval), or `globalThis` (as if it's run in a separate global script) for indirect eval.
```js
function test() {
// Direct eval
console.log(eval("this") === this);
// Indirect eval, non-strict
console.log(eval?.("this") === globalThis);
// Indirect eval, strict
console.log(eval?.("'use strict'; this") === globalThis);
}
test.call({ name: "obj" }); // Logs 3 "true"
```
Note that some source code, while looking like the global scope, is actually wrapped in a function when executed. For example, Node.js CommonJS modules are wrapped in a function and executed with the `this` value set to `module.exports`. [Event handler attributes](#this_in_inline_event_handlers) are executed with `this` set to the element they are attached to.
Object literals don't create a `this` scope β only functions (methods) defined within the object do. Using `this` in an object literal inherits the value from the surrounding scope.
```js
const obj = {
a: this,
};
console.log(obj.a === window); // true
```
## Examples
### this in function contexts
The value of the `this` parameter depends on how the function is called, not on how it's defined.
```js
// An object can be passed as the first argument to 'call'
// or 'apply' and 'this' will be bound to it.
const obj = { a: "Custom" };
// Variables declared with var become properties of 'globalThis'.
var a = "Global";
function whatsThis() {
return this.a; // 'this' depends on how the function is called
}
whatsThis(); // 'Global'; the 'this' parameter defaults to 'globalThis' in nonβstrict mode
obj.whatsThis = whatsThis;
obj.whatsThis(); // 'Custom'; the 'this' parameter is bound to obj
```
Using `call()` and `apply()`, you can pass the value of `this` as if it's an explicit parameter.
```js
function add(c, d) {
return this.a + this.b + c + d;
}
const o = { a: 1, b: 3 };
// The first argument is bound to the implicit 'this' parameter; the remaining
// arguments are bound to the named parameters.
add.call(o, 5, 7); // 16
// The first argument is bound to the implicit 'this' parameter; the second
// argument is an array whose members are bound to the named parameters.
add.apply(o, [10, 20]); // 34
```
### this and object conversion
In nonβstrict mode, if a function is called with a `this` value that's not an object, the `this` value is substituted with an object. `null` and `undefined` become `globalThis`. Primitives like `7` or `'foo'` are converted to an object using the related constructor, so the primitive number `7` is converted to a {{jsxref("Number")}} wrapper class and the string `'foo'` to a {{jsxref("String")}} wrapper class.
```js
function bar() {
console.log(Object.prototype.toString.call(this));
}
bar.call(7); // [object Number]
bar.call("foo"); // [object String]
bar.call(undefined); // [object Window]
```
### The bind() method
Calling [`f.bind(someObject)`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) creates a new function with the same body and scope as `f`, but the value of `this` is permanently bound to the first argument of `bind`, regardless of how the function is being called.
```js
function f() {
return this.a;
}
const g = f.bind({ a: "azerty" });
console.log(g()); // azerty
const h = g.bind({ a: "yoo" }); // bind only works once!
console.log(h()); // azerty
const o = { a: 37, f, g, h };
console.log(o.a, o.f(), o.g(), o.h()); // 37 37 azerty azerty
```
### this in arrow functions
Arrow functions create closures over the `this` value of the enclosing execution context. In the following example, we create `obj` with a method `getThisGetter` that returns a function that returns the value of `this`. The returned function is created as an arrow function, so its `this` is permanently bound to the `this` of its enclosing function. The value of `this` inside `getThisGetter` can be set in the call, which in turn sets the return value of the returned function. We will assume that `getThisGetter` is a non-strict function, which means it's contained in a non-strict script and not further nested in a class or strict function.
```js
const obj = {
getThisGetter() {
const getter = () => this;
return getter;
},
};
```
We can call `getThisGetter` as a method of `obj`, which binds `this` to `obj` inside its body. The returned function is assigned to a variable `fn`. Now, when calling `fn`, the value of `this` returned is still the one set by the call to `getThisGetter`, which is `obj`. If the returned function was not an arrow function, such calls would cause the `this` value to be `globalThis`, because `getThisGetter` is non-strict.
```js
const fn = obj.getThisGetter();
console.log(fn() === obj); // true
```
But be careful if you unbind the method of `obj` without calling it, because `getThisGetter` is still a method that has a varying `this` value. Calling `fn2()()` in the following example returns `globalThis`, because it follows the `this` from `fn2()`, which is `globalThis` since it's called without being attached to any object.
```js
const fn2 = obj.getThisGetter;
console.log(fn2()() === globalThis); // true in non-strict mode
```
This behavior is very useful when defining callbacks. Usually, each function expression creates its own `this` binding, which shadows the `this` value of the upper scope. Now, you can define functions as arrow functions if you don't care about the `this` value, and only create `this` bindings where you do (e.g. in class methods). See [example with `setTimeout()`](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#using_call_bind_and_apply).
### this with a getter or setter
`this` in getters and setters is based on which object the property is accessed on, not which object the property is defined on. A function used as getter or setter has its `this` bound to the object from which the property is being set or gotten.
```js
function sum() {
return this.a + this.b + this.c;
}
const o = {
a: 1,
b: 2,
c: 3,
get average() {
return (this.a + this.b + this.c) / 3;
},
};
Object.defineProperty(o, "sum", {
get: sum,
enumerable: true,
configurable: true,
});
console.log(o.average, o.sum); // 2 6
```
### this in DOM event handlers
When a function is used as an event handler, its `this` parameter is bound to the DOM element on which the listener is placed (some browsers do not follow this convention for listeners added dynamically with methods other than {{domxref("EventTarget/addEventListener", "addEventListener()")}}).
```js
// When called as a listener, turns the related element blue
function bluify(e) {
// Always true
console.log(this === e.currentTarget);
// true when currentTarget and target are the same object
console.log(this === e.target);
this.style.backgroundColor = "#A5D9F3";
}
// Get a list of every element in the document
const elements = document.getElementsByTagName("*");
// Add bluify as a click listener so when the
// element is clicked on, it turns blue
for (const element of elements) {
element.addEventListener("click", bluify, false);
}
```
### this in inline event handlers
When the code is called from an inline [event handler attribute](/en-US/docs/Web/HTML/Attributes#event_handler_attributes), its `this` is bound to the DOM element on which the listener is placed:
```html
<button onclick="alert(this.tagName.toLowerCase());">Show this</button>
```
The above alert shows `button`. Note, however, that only the outer scope has its `this` bound this way:
```html
<button onclick="alert((function () { return this; })());">
Show inner this
</button>
```
In this case, the `this` parameter of the inner function is bound to `globalThis` (i.e. the default object in nonβstrict mode where `this` isn't passed in the call).
### Bound methods in classes
Just like with regular functions, the value of `this` within methods depends on how they are called. Sometimes it is useful to override this behavior so that `this` within classes always refers to the class instance. To achieve this, bind the class methods in the constructor:
```js
class Car {
constructor() {
// Bind sayBye but not sayHi to show the difference
this.sayBye = this.sayBye.bind(this);
}
sayHi() {
console.log(`Hello from ${this.name}`);
}
sayBye() {
console.log(`Bye from ${this.name}`);
}
get name() {
return "Ferrari";
}
}
class Bird {
get name() {
return "Tweety";
}
}
const car = new Car();
const bird = new Bird();
// The value of 'this' in methods depends on their caller
car.sayHi(); // Hello from Ferrari
bird.sayHi = car.sayHi;
bird.sayHi(); // Hello from Tweety
// For bound methods, 'this' doesn't depend on the caller
bird.sayBye = car.sayBye;
bird.sayBye(); // Bye from Ferrari
```
> **Note:** Classes are always in strict mode. Calling methods with an undefined `this` will throw an error if the method tries to access properties on `this`.
>
> ```js example-bad
> const carSayHi = car.sayHi;
> carSayHi(); // TypeError because the 'sayHi' method tries to access 'this.name', but 'this' is undefined in strict mode.
> ```
Note, however, that auto-bound methods suffer from the same problem as [using arrow functions for class properties](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#cannot_be_used_as_methods): each instance of the class will have its own copy of the method, which increases memory usage. Only use it where absolutely necessary. You can also mimic the implementation of [`Intl.NumberFormat.prototype.format()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format#using_format_with_map): define the property as a getter that returns a bound function when accessed and saves it, so that the function is only created once and only created when necessary.
### this in with statements
Although [`with`](/en-US/docs/Web/JavaScript/Reference/Statements/with) statements are deprecated and not available in strict mode, they still serve as an exception to the normal `this` binding rules. If a function is called within a `with` statement and that function is a property of the scope object, the `this` value is bound to the scope object, as if the `obj1.` prefix exists.
```js
const obj1 = {
foo() {
return this;
},
};
with (obj1) {
console.log(foo() === obj1); // true
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode)
- {{jsxref("globalThis")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/async_function/index.md | ---
title: async function expression
slug: Web/JavaScript/Reference/Operators/async_function
page-type: javascript-operator
browser-compat: javascript.operators.async_function
---
{{jsSidebar("Operators")}}
The **`async function`** keywords can be used to define an async function inside an expression.
You can also define async functions using the [`async function` declaration](/en-US/docs/Web/JavaScript/Reference/Statements/async_function) or the [arrow syntax](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions).
## Syntax
```js-nolint
async function (param0) {
statements
}
async function (param0, param1) {
statements
}
async function (param0, param1, /* β¦, */ paramN) {
statements
}
async function name(param0) {
statements
}
async function name(param0, param1) {
statements
}
async function name(param0, param1, /* β¦, */ paramN) {
statements
}
```
> **Note:** An [expression statement](/en-US/docs/Web/JavaScript/Reference/Statements/Expression_statement) cannot begin with the keywords `async function` to avoid ambiguity with an [`async function` declaration](/en-US/docs/Web/JavaScript/Reference/Statements/async_function). The `async function` keywords only begin an expression when they appear in a context that cannot accept statements.
### Parameters
- `name` {{optional_inline}}
- : The function name. Can be omitted, in which case the function is _anonymous_. The name is only local to the function body.
- `paramN` {{optional_inline}}
- : The name of a formal parameter for the function. For the parameters' syntax, see the [Functions reference](/en-US/docs/Web/JavaScript/Guide/Functions#function_parameters).
- `statements` {{optional_inline}}
- : The statements which comprise the body of the function.
## Description
An `async function` expression is very similar to, and has almost the same syntax as, an [`async function` declaration](/en-US/docs/Web/JavaScript/Reference/Statements/async_function). The main difference between an `async function` expression and an `async function` declaration is the _function name_, which can be omitted in `async function` expressions to create _anonymous_ functions. An `async function` expression can be used as an [IIFE](/en-US/docs/Glossary/IIFE) (Immediately Invoked Function Expression) which runs as soon as it is defined, allowing you to mimic [top-level await](/en-US/docs/Web/JavaScript/Guide/Modules#top_level_await). See also the chapter about [functions](/en-US/docs/Web/JavaScript/Reference/Functions) for more information.
## Examples
### Using async function expression
```js
function resolveAfter2Seconds(x) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
// async function expression assigned to a variable
const add = async function (x) {
const a = await resolveAfter2Seconds(20);
const b = await resolveAfter2Seconds(30);
return x + a + b;
};
add(10).then((v) => {
console.log(v); // prints 60 after 4 seconds.
});
// async function expression used as an IIFE
(async function (x) {
const p1 = resolveAfter2Seconds(20);
const p2 = resolveAfter2Seconds(30);
return x + (await p1) + (await p2);
})(10).then((v) => {
console.log(v); // prints 60 after 2 seconds.
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Functions](/en-US/docs/Web/JavaScript/Guide/Functions) guide
- [Functions](/en-US/docs/Web/JavaScript/Reference/Functions)
- {{jsxref("Statements/async_function", "async function")}}
- {{jsxref("AsyncFunction")}}
- {{jsxref("Operators/await", "await")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/unsigned_right_shift/index.md | ---
title: Unsigned right shift (>>>)
slug: Web/JavaScript/Reference/Operators/Unsigned_right_shift
page-type: javascript-operator
browser-compat: javascript.operators.unsigned_right_shift
---
{{jsSidebar("Operators")}}
The **unsigned right shift (`>>>`)** operator returns a number whose binary representation is the first operand shifted by the specified number of bits to the right. Excess bits shifted off to the right are discarded, and zero bits are shifted in from the left. This operation is also called "zero-filling right shift", because the sign bit becomes `0`, so the resulting number is always positive. Unsigned right shift does not accept [BigInt](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) values.
{{EmbedInteractiveExample("pages/js/expressions-unsigned-right-shift.html")}}
## Syntax
```js-nolint
x >>> y
```
## Description
Unlike other arithmetic and bitwise operators, the unsigned right shift operator does not accept [BigInt](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) values. This is because it fills the leftmost bits with zeroes, but conceptually, BigInts have an infinite number of leading sign bits, so there's no "leftmost bit" to fill with zeroes.
The operator operates on the left operand's bit representation in [two's complement](https://en.wikipedia.org/wiki/Two's_complement). Consider the 32-bit binary representations of the decimal (base 10) numbers `9` and `-9`:
```plain
9 (base 10): 00000000000000000000000000001001 (base 2)
-9 (base 10): 11111111111111111111111111110111 (base 2)
```
The binary representation under two's complement of the negative decimal (base 10) number `-9` is formed by inverting all the bits of its opposite number, which is `9` and `00000000000000000000000000001001` in binary, and adding `1`.
In both cases, the sign of the binary number is given by its leftmost bit: for the positive decimal number `9`, the leftmost bit of the binary representation is `0`, and for the negative decimal number `-9`, the leftmost bit of the binary representation is `1`.
Given those binary representations of the decimal (base 10) numbers `9`, and `-9`:
For the positive number `9`, zero-fill right shift and [sign-propagating right shift](/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift) yield the same result: `9 >>> 2` yields `2`, the same as `9 >> 2`:
```plain
9 (base 10): 00000000000000000000000000001001 (base 2)
--------------------------------
9 >> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
9 >>> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
```
Notice how two rightmost bits, `01`, have been shifted off, and two zeroes have been shifted in from the left.
However, notice what happens for `-9`: `-9 >> 2` ([sign-propagating right shift](/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift)) yields `-3`, but `-9 >>> 2` (zero-fill right shift) yields 1073741821:
```plain
-9 (base 10): 11111111111111111111111111110111 (base 2)
--------------------------------
-9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)
-9 >>> 2 (base 10): 00111111111111111111111111111101 (base 2) = 1073741821 (base 10)
```
Notice how two rightmost bits, `11`, have been shifted off. For `-9 >> 2` ([sign-propagating right shift](/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift)), two copies of the leftmost `1` bit have been shifted in from the left, which preserves the negative sign. On the other hand, for `-9 >>> 2` (zero-fill right shift), zeroes have instead been shifted in from the left, so the negative sign of the number is not preserved, and the result is instead a (large) positive number.
If the left operand is a number with more than 32 bits, it will get the most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32-bit integer:
```plain
Before: 11100110111110100000000000000110000000000001
After: 10100000000000000110000000000001
```
The right operand will be converted to an unsigned 32-bit integer and then taken modulo 32, so the actual shift offset will always be a positive integer between 0 and 31, inclusive. For example, `100 >>> 32` is the same as `100 >>> 0` (and produces `100`) because 32 modulo 32 is 0.
## Examples
### Using unsigned right shift
```js
9 >>> 2; // 2
-9 >>> 2; // 1073741821
```
Unsigned right shift doesn't work with BigInts.
```js
9n >>> 2n; // TypeError: BigInts have no unsigned right shift, use >> instead
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Bitwise operators in the JS guide](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#bitwise_operators)
- [Unsigned right shift assignment (`>>>=`)](/en-US/docs/Web/JavaScript/Reference/Operators/Unsigned_right_shift_assignment)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/bitwise_and_assignment/index.md | ---
title: Bitwise AND assignment (&=)
slug: Web/JavaScript/Reference/Operators/Bitwise_AND_assignment
page-type: javascript-operator
browser-compat: javascript.operators.bitwise_and_assignment
---
{{jsSidebar("Operators")}}
The **bitwise AND assignment (`&=`)** operator performs [bitwise AND](/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND) on the two operands and assigns the result to the left operand.
{{EmbedInteractiveExample("pages/js/expressions-bitwise-and-assignment.html", "shorter")}}
## Syntax
```js-nolint
x &= y
```
## Description
`x &= y` is equivalent to `x = x & y`, except that the expression `x` is only evaluated once.
## Examples
### Using bitwise AND assignment
```js
let a = 5;
// 5: 00000000000000000000000000000101
// 2: 00000000000000000000000000000010
a &= 2; // 0
let b = 5n;
b &= 2n; // 0n
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Assignment operators in the JS guide](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#assignment_operators)
- [Bitwise AND (`&`)](/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/inequality/index.md | ---
title: Inequality (!=)
slug: Web/JavaScript/Reference/Operators/Inequality
page-type: javascript-operator
browser-compat: javascript.operators.inequality
---
{{jsSidebar("Operators")}}
The **inequality (`!=`)** operator checks whether its two operands are not
equal, returning a Boolean result.
Unlike the [strict inequality](/en-US/docs/Web/JavaScript/Reference/Operators/Strict_inequality) operator,
it attempts to convert and compare operands that are of different types.
{{EmbedInteractiveExample("pages/js/expressions-inequality.html")}}
## Syntax
```js-nolint
x != y
```
## Description
The inequality operator checks whether its operands are not equal. It is the negation
of the [equality](/en-US/docs/Web/JavaScript/Reference/Operators/Equality)
operator so the following two lines will always give the same result:
```js
x != y;
!(x == y);
```
For details of the comparison algorithm, see the page for the [equality](/en-US/docs/Web/JavaScript/Reference/Operators/Equality) operator.
Like the equality operator, the inequality operator will attempt to convert and compare
operands of different types:
```js
3 != "3"; // false
```
To prevent this, and require that different types are considered to be different, use
the [strict inequality](/en-US/docs/Web/JavaScript/Reference/Operators/Strict_inequality) operator instead:
```js
3 !== "3"; // true
```
## Examples
### Comparison with no type conversion
```js
1 != 2; // true
"hello" != "hola"; // true
1 != 1; // false
"hello" != "hello"; // false
```
### Comparison with type conversion
```js
"1" != 1; // false
1 != "1"; // false
0 != false; // false
0 != null; // true
0 != undefined; // true
0 != !!null; // false, look at Logical NOT operator
0 != !!undefined; // false, look at Logical NOT operator
null != undefined; // false
const number1 = new Number(3);
const number2 = new Number(3);
number1 != 3; // false
number1 != number2; // true
```
### Comparison of objects
```js
const object1 = {
key: "value",
};
const object2 = {
key: "value",
};
console.log(object1 != object2); // true
console.log(object1 != object1); // false
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Equality (`==`)](/en-US/docs/Web/JavaScript/Reference/Operators/Equality)
- [Strict equality (`===`)](/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality)
- [Strict inequality (`!==`)](/en-US/docs/Web/JavaScript/Reference/Operators/Strict_inequality)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/remainder/index.md | ---
title: Remainder (%)
slug: Web/JavaScript/Reference/Operators/Remainder
page-type: javascript-operator
browser-compat: javascript.operators.remainder
---
{{jsSidebar("Operators")}}
The **remainder (`%`)** operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.
{{EmbedInteractiveExample("pages/js/expressions-remainder.html")}}
## Syntax
```js-nolint
x % y
```
## Description
The `%` operator is overloaded for two types of operands: number and [BigInt](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt). It first [coerces both operands to numeric values](/en-US/docs/Web/JavaScript/Data_structures#numeric_coercion) and tests the types of them. It performs BigInt remainder if both operands become BigInts; otherwise, it performs number remainder. A {{jsxref("TypeError")}} is thrown if one operand becomes a BigInt but the other becomes a number.
For the operation `n % d`, `n` is called the dividend and `d` is called the divisor. The operation returns `NaN` if one of the operands is `NaN`, `n` is Β±Infinity, or if `d` is Β±0. Otherwise, if `d` is Β±Infinity or if `n` is Β±0, the dividend `n` is returned.
When both operands are non-zero and finite, the remainder `r` is calculated as `r := n - d * q` where `q` is the integer such that `r` has the same sign as the dividend `n` while being as close to 0 as possible.
Note that while in most languages, '%' is a remainder operator, in some (e.g. [Python, Perl](https://en.wikipedia.org/wiki/Modulo_operation#In_programming_languages)) it is a modulo operator. Modulo is defined as `k := n - d * q` where `q` is the integer such that `k` has the same sign as the divisor `d` while being as close to 0 as possible. For two values of the same sign, the two are equivalent, but when the operands are of different signs, the modulo result always has the same sign as the _divisor_, while the remainder has the same sign as the _dividend_, which can make them differ by one unit of `d`. To obtain a modulo in JavaScript, in place of `n % d`, use `((n % d) + d) % d`. In JavaScript, the modulo operation (which doesn't have a dedicated operator) is used to normalize the second operand of bitwise shift operators ([`<<`](/en-US/docs/Web/JavaScript/Reference/Operators/Left_shift), [`>>`](/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift), etc.), making the offset always a positive value.
For BigInt division, a {{jsxref("RangeError")}} is thrown if the divisor `y` is `0n`. This is because number remainder by zero returns `NaN`, but BigInt has no concept of `NaN`.
## Examples
### Remainder with positive dividend
```js
13 % 5; // 3
1 % -2; // 1
1 % 2; // 1
2 % 3; // 2
5.5 % 2; // 1.5
3n % 2n; // 1n
```
### Remainder with negative dividend
```js
-13 % 5; // -3
-1 % 2; // -1
-4 % 2; // -0
-3n % 2n; // -1n
```
### Remainder with NaN
```js
NaN % 2; // NaN
```
### Remainder with Infinity
```js
Infinity % 2; // NaN
Infinity % 0; // NaN
Infinity % Infinity; // NaN
2 % Infinity; // 2
0 % Infinity; // 0
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Addition (`+`)](/en-US/docs/Web/JavaScript/Reference/Operators/Addition)
- [Subtraction (`-`)](/en-US/docs/Web/JavaScript/Reference/Operators/Subtraction)
- [Division (`/`)](/en-US/docs/Web/JavaScript/Reference/Operators/Division)
- [Multiplication (`*`)](/en-US/docs/Web/JavaScript/Reference/Operators/Multiplication)
- [Exponentiation (`**`)](/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation)
- [Increment (`++`)](/en-US/docs/Web/JavaScript/Reference/Operators/Increment)
- [Decrement (`--`)](/en-US/docs/Web/JavaScript/Reference/Operators/Decrement)
- [Unary negation (`-`)](/en-US/docs/Web/JavaScript/Reference/Operators/Unary_negation)
- [Unary plus (`+`)](/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus)
- [Remainder operator vs. modulo operator](https://2ality.com/2019/08/remainder-vs-modulo.html) by Dr. Axel Rauschmayer (2019)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/null/index.md | ---
title: "null"
slug: Web/JavaScript/Reference/Operators/null
page-type: javascript-language-feature
browser-compat: javascript.operators.null
---
{{jsSidebar("Operators")}}
The **`null`** value represents the intentional absence of any object value. It
is one of JavaScript's [primitive values](/en-US/docs/Glossary/Primitive) and
is treated as [falsy](/en-US/docs/Glossary/Falsy) for boolean operations.
{{EmbedInteractiveExample("pages/js/globalprops-null.html")}}
## Syntax
```js-nolint
null
```
## Description
The value `null` is written with a literal: `null`.
`null` is not an identifier for a property of the global object, like
{{jsxref("undefined")}} can be. Instead,
`null` expresses a lack of identification, indicating that a variable points
to no object. In APIs, `null` is often retrieved in a place where an object
can be expected but no object is relevant.
```js
// foo does not exist. It is not defined and has never been initialized:
foo; //ReferenceError: foo is not defined
```
```js
// foo is known to exist now but it has no type or value:
const foo = null;
foo; //null
```
## Examples
### Difference between `null` and `undefined`
When checking for `null` or `undefined`, beware of the [differences between equality (==) and identity (===) operators](/en-US/docs/Web/JavaScript/Reference/Operators), as the former performs
type-conversion.
```js
typeof null; // "object" (not "null" for legacy reasons)
typeof undefined; // "undefined"
null === undefined; // false
null == undefined; // true
null === null; // true
null == null; // true
!null; // true
Number.isNaN(1 + null); // false
Number.isNaN(1 + undefined); // true
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("undefined")}}
- {{jsxref("NaN")}}
- {{jsxref("Operators/void", "void")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/conditional_operator/index.md | ---
title: Conditional (ternary) operator
slug: Web/JavaScript/Reference/Operators/Conditional_operator
page-type: javascript-operator
browser-compat: javascript.operators.conditional
---
{{jsSidebar("Operators")}}
The **conditional (ternary) operator** is the only JavaScript operator that takes three operands:
a condition followed by a question mark (`?`), then an expression to execute if the condition is {{Glossary("truthy")}} followed by a colon (`:`), and finally the expression to execute if the condition is {{Glossary("falsy")}}.
This operator is frequently used as an alternative to an [`if...else`](/en-US/docs/Web/JavaScript/Reference/Statements/if...else) statement.
{{EmbedInteractiveExample("pages/js/expressions-conditionaloperators.html")}}
## Syntax
```js-nolint
condition ? exprIfTrue : exprIfFalse
```
### Parameters
- `condition`
- : An expression whose value is used as a condition.
- `exprIfTrue`
- : An expression which is executed if the `condition` evaluates to a {{Glossary("truthy")}} value (one which equals or can be converted to `true`).
- `exprIfFalse`
- : An expression which is executed if the `condition` is {{Glossary("falsy")}} (that is, has a value which can be converted to `false`).
## Description
Besides `false`, possible falsy expressions are: `null`, `NaN`, `0`, the empty string (`""`), and `undefined`.
If `condition` is any of these, the result of the conditional expression will be the result of executing the expression `exprIfFalse`.
## Examples
### A simple example
```js
const age = 26;
const beverage = age >= 21 ? "Beer" : "Juice";
console.log(beverage); // "Beer"
```
### Handling null values
One common usage is to handle a value that may be `null`:
```js
const greeting = (person) => {
const name = person ? person.name : "stranger";
return `Howdy, ${name}`;
};
console.log(greeting({ name: "Alice" })); // "Howdy, Alice"
console.log(greeting(null)); // "Howdy, stranger"
```
### Conditional chains
The ternary operator is right-associative, which means it can be "chained" in the following way, similar to an `if β¦ else if β¦ else if β¦ else` chain:
```js-nolint
function example() {
return condition1 ? value1
: condition2 ? value2
: condition3 ? value3
: value4;
}
```
This is equivalent to the following [`if...else`](/en-US/docs/Web/JavaScript/Reference/Statements/if...else) chain.
```js
function example() {
if (condition1) {
return value1;
} else if (condition2) {
return value2;
} else if (condition3) {
return value3;
} else {
return value4;
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`if...else`](/en-US/docs/Web/JavaScript/Reference/Statements/if...else)
- [Nullish coalescing operator (`??`)](/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing)
- [Optional chaining (`?.`)](/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)
- [Making decisions in your code β conditionals](/en-US/docs/Learn/JavaScript/Building_blocks/conditionals)
- [Expressions and operators](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators) guide
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/left_shift_assignment/index.md | ---
title: Left shift assignment (<<=)
slug: Web/JavaScript/Reference/Operators/Left_shift_assignment
page-type: javascript-operator
browser-compat: javascript.operators.left_shift_assignment
---
{{jsSidebar("Operators")}}
The **left shift assignment (`<<=`)** operator performs [left shift](/en-US/docs/Web/JavaScript/Reference/Operators/Left_shift) on the two operands and assigns the result to the left operand.
{{EmbedInteractiveExample("pages/js/expressions-left-shift-assignment.html", "shorter")}}
## Syntax
```js-nolint
x <<= y
```
## Description
`x <<= y` is equivalent to `x = x << y`, except that the expression `x` is only evaluated once.
## Examples
### Using left shift assignment
```js
let a = 5;
// 00000000000000000000000000000101
a <<= 2; // 20
// 00000000000000000000000000010100
let b = 5n;
b <<= 2n; // 20n
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Assignment operators in the JS guide](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#assignment_operators)
- [Left shift (`<<`)](/en-US/docs/Web/JavaScript/Reference/Operators/Left_shift)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/decrement/index.md | ---
title: Decrement (--)
slug: Web/JavaScript/Reference/Operators/Decrement
page-type: javascript-operator
browser-compat: javascript.operators.decrement
---
{{jsSidebar("Operators")}}
The **decrement (`--`)** operator decrements (subtracts one from) its operand and returns the value before or after the decrement, depending on where the operator is placed.
{{EmbedInteractiveExample("pages/js/expressions-decrement.html")}}
## Syntax
```js-nolint
x--
--x
```
## Description
The `--` operator is overloaded for two types of operands: number and [BigInt](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt). It first [coerces the operand to a numeric value](/en-US/docs/Web/JavaScript/Data_structures#numeric_coercion) and tests the type of it. It performs BigInt decrement if the operand becomes a BigInt; otherwise, it performs number decrement.
If used postfix, with operator after operand (for example, `x--`), the decrement operator decrements and returns the value before decrementing.
If used prefix, with operator before operand (for example, `--x`), the decrement operator decrements and returns the value after decrementing.
The decrement operator can only be applied on operands that are references (variables and object properties; i.e. valid [assignment targets](/en-US/docs/Web/JavaScript/Reference/Operators/Assignment)). `--x` itself evaluates to a value, not a reference, so you cannot chain multiple decrement operators together.
```js-nolint example-bad
--(--x); // SyntaxError: Invalid left-hand side expression in prefix operation
```
## Examples
### Postfix decrement
```js
let x = 3;
const y = x--;
// x is 2; y is 3
let x2 = 3n;
const y2 = x2--;
// x2 is 2n; y2 is 3n
```
### Prefix decrement
```js
let x = 3;
const y = --x;
// x is 2; y = 2
let x2 = 3n;
const y2 = --x2;
// x2 is 2n; y2 is 2n
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Addition (`+`)](/en-US/docs/Web/JavaScript/Reference/Operators/Addition)
- [Subtraction (`-`)](/en-US/docs/Web/JavaScript/Reference/Operators/Subtraction)
- [Division (`/`)](/en-US/docs/Web/JavaScript/Reference/Operators/Division)
- [Multiplication (`*`)](/en-US/docs/Web/JavaScript/Reference/Operators/Multiplication)
- [Remainder (`%`)](/en-US/docs/Web/JavaScript/Reference/Operators/Remainder)
- [Exponentiation (`**`)](/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation)
- [Increment (`++`)](/en-US/docs/Web/JavaScript/Reference/Operators/Increment)
- [Unary negation (`-`)](/en-US/docs/Web/JavaScript/Reference/Operators/Unary_negation)
- [Unary plus (`+`)](/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/function/index.md | ---
title: function expression
slug: Web/JavaScript/Reference/Operators/function
page-type: javascript-operator
browser-compat: javascript.operators.function
---
{{jsSidebar("Operators")}}
The **`function`** keyword can be used to define a function inside an expression.
You can also define functions using the [`function` declaration](/en-US/docs/Web/JavaScript/Reference/Statements/function) or the [arrow syntax](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions).
{{EmbedInteractiveExample("pages/js/expressions-functionexpression.html", "shorter")}}
## Syntax
```js-nolint
function (param0) {
statements
}
function (param0, param1) {
statements
}
function (param0, param1, /* β¦, */ paramN) {
statements
}
function name(param0) {
statements
}
function name(param0, param1) {
statements
}
function name(param0, param1, /* β¦, */ paramN) {
statements
}
```
> **Note:** An [expression statement](/en-US/docs/Web/JavaScript/Reference/Statements/Expression_statement) cannot begin with the keyword `function` to avoid ambiguity with a [`function` declaration](/en-US/docs/Web/JavaScript/Reference/Statements/function). The `function` keyword only begins an expression when it appears in a context that cannot accept statements.
### Parameters
- `name` {{optional_inline}}
- : The function name. Can be omitted, in which case the function is _anonymous_. The name is only local to the function body.
- `paramN` {{optional_inline}}
- : The name of a formal parameter for the function. For the parameters' syntax, see the [Functions reference](/en-US/docs/Web/JavaScript/Guide/Functions#function_parameters).
- `statements` {{optional_inline}}
- : The statements which comprise the body of the function.
## Description
A `function` expression is very similar to, and has almost the same syntax as, a [`function` declaration](/en-US/docs/Web/JavaScript/Reference/Statements/function). The main difference between a `function` expression and a `function` declaration is the _function name_, which can be omitted in `function` expressions to create _anonymous_ functions. A `function` expression can be used as an [IIFE](/en-US/docs/Glossary/IIFE) (Immediately Invoked Function Expression) which runs as soon as it is defined. See also the chapter about [functions](/en-US/docs/Web/JavaScript/Reference/Functions) for more information.
### Function expression hoisting
Function expressions in JavaScript are not hoisted, unlike [function declarations](/en-US/docs/Web/JavaScript/Reference/Statements/function#hoisting). You can't use function expressions before you create them:
```js
console.log(notHoisted); // undefined
// Even though the variable name is hoisted,
// the definition isn't. so it's undefined.
notHoisted(); // TypeError: notHoisted is not a function
var notHoisted = function () {
console.log("bar");
};
```
### Named function expression
If you want to refer to the current function inside the function body, you need to create a named function expression. This name is then local only to the function body (scope). This avoids using the deprecated {{jsxref("Functions/arguments/callee", "arguments.callee")}} property to call the function recursively.
```js
const math = {
factit: function factorial(n) {
console.log(n);
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
},
};
math.factit(3); //3;2;1;
```
If a function expression is named, the [`name`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name) property of the function is set to that name, instead of the implicit name inferred from syntax (such as the variable the function is assigned to).
Unlike declarations, the name of the function expressions is read-only.
```js
function foo() {
foo = 1;
}
foo();
console.log(foo); // 1
(function foo() {
foo = 1; // TypeError: Assignment to constant variable.
})();
```
## Examples
### Using function expression
The following example defines an unnamed function and assigns it to `x`. The function returns the square of its argument:
```js
const x = function (y) {
return y * y;
};
```
### Using a function as a callback
More commonly it is used as a {{Glossary("Callback_function", "callback")}}:
```js
button.addEventListener("click", function (event) {
console.log("button is clicked!");
});
```
### Using an Immediately Invoked Function Expression (IIFE)
An anonymous function is created and called:
```js-nolint
(function () {
console.log("Code runs!");
})();
// or
!function () {
console.log("Code runs!");
}();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Functions](/en-US/docs/Web/JavaScript/Guide/Functions) guide
- [Functions](/en-US/docs/Web/JavaScript/Reference/Functions)
- {{jsxref("Statements/function", "function")}}
- {{jsxref("Function")}}
- {{jsxref("Functions/Arrow_functions", "Arrow functions", "", 1)}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/destructuring_assignment/index.md | ---
title: Destructuring assignment
slug: Web/JavaScript/Reference/Operators/Destructuring_assignment
page-type: javascript-language-feature
browser-compat: javascript.operators.destructuring
---
{{jsSidebar("Operators")}}
The **destructuring assignment** syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
{{EmbedInteractiveExample("pages/js/expressions-destructuringassignment.html", "taller")}}
## Syntax
```js-nolint
const [a, b] = array;
const [a, , b] = array;
const [a = aDefault, b] = array;
const [a, b, ...rest] = array;
const [a, , b, ...rest] = array;
const [a, b, ...{ pop, push }] = array;
const [a, b, ...[c, d]] = array;
const { a, b } = obj;
const { a: a1, b: b1 } = obj;
const { a: a1 = aDefault, b = bDefault } = obj;
const { a, b, ...rest } = obj;
const { a: a1, b: b1, ...rest } = obj;
const { [key]: a } = obj;
let a, b, a1, b1, c, d, rest, pop, push;
[a, b] = array;
[a, , b] = array;
[a = aDefault, b] = array;
[a, b, ...rest] = array;
[a, , b, ...rest] = array;
[a, b, ...{ pop, push }] = array;
[a, b, ...[c, d]] = array;
({ a, b } = obj); // parentheses are required
({ a: a1, b: b1 } = obj);
({ a: a1 = aDefault, b = bDefault } = obj);
({ a, b, ...rest } = obj);
({ a: a1, b: b1, ...rest } = obj);
```
## Description
The object and array literal expressions provide an easy way to create _ad hoc_ packages of data.
```js
const x = [1, 2, 3, 4, 5];
```
The destructuring assignment uses similar syntax but uses it on the left-hand side of the assignment instead. It defines which values to unpack from the sourced variable.
```js
const x = [1, 2, 3, 4, 5];
const [y, z] = x;
console.log(y); // 1
console.log(z); // 2
```
Similarly, you can destructure objects on the left-hand side of the assignment.
```js
const obj = { a: 1, b: 2 };
const { a, b } = obj;
// is equivalent to:
// const a = obj.a;
// const b = obj.b;
```
This capability is similar to features present in languages such as Perl and Python.
For features specific to array or object destructuring, refer to the individual [examples](#examples) below.
### Binding and assignment
For both object and array destructuring, there are two kinds of destructuring patterns: _{{Glossary("binding")}} pattern_ and _assignment pattern_, with slightly different syntaxes.
In binding patterns, the pattern starts with a declaration keyword (`var`, `let`, or `const`). Then, each individual property must either be bound to a variable or further destructured.
```js
const obj = { a: 1, b: { c: 2 } };
const {
a,
b: { c: d },
} = obj;
// Two variables are bound: `a` and `d`
```
All variables share the same declaration, so if you want some variables to be re-assignable but others to be read-only, you may have to destructure twice β once with `let`, once with `const`.
```js
const obj = { a: 1, b: { c: 2 } };
const { a } = obj; // a is constant
let {
b: { c: d },
} = obj; // d is re-assignable
```
In many other syntaxes where the language binds a variable for you, you can use a binding destructuring pattern. These include:
- The looping variable of [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in) [`for...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for...of), and [`for await...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of) loops;
- [Function](/en-US/docs/Web/JavaScript/Reference/Functions) parameters;
- The [`catch`](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch) binding variable.
In assignment patterns, the pattern does not start with a keyword. Each destructured property is assigned to a target of assignment β which may either be declared beforehand with `var` or `let`, or is a property of another object β in general, anything that can appear on the left-hand side of an assignment expression.
```js
const numbers = [];
const obj = { a: 1, b: 2 };
({ a: numbers[0], b: numbers[1] } = obj);
// The properties `a` and `b` are assigned to properties of `numbers`
```
> **Note:** The parentheses `( ... )` around the assignment statement are required when using object literal destructuring assignment without a declaration.
>
> `{ a, b } = { a: 1, b: 2 }` is not valid stand-alone syntax, as the `{ a, b }` on the left-hand side is considered a block and not an object literal according to the rules of [expression statements](/en-US/docs/Web/JavaScript/Reference/Statements/Expression_statement). However, `({ a, b } = { a: 1, b: 2 })` is valid, as is `const { a, b } = { a: 1, b: 2 }`.
>
> If your coding style does not include trailing semicolons, the `( ... )` expression needs to be preceded by a semicolon, or it may be used to execute a function on the previous line.
Note that the equivalent _binding pattern_ of the code above is not valid syntax:
```js-nolint example-bad
const numbers = [];
const obj = { a: 1, b: 2 };
const { a: numbers[0], b: numbers[1] } = obj;
// This is equivalent to:
// const numbers[0] = obj.a;
// const numbers[1] = obj.b;
// Which definitely is not valid.
```
You can only use assignment patterns as the left-hand side of the [assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Assignment) operator. You cannot use them with compound assignment operators such as `+=` or `*=`.
### Default value
Each destructured property can have a _default value_. The default value is used when the property is not present, or has value `undefined`. It is not used if the property has value `null`.
```js
const [a = 1] = []; // a is 1
const { b = 2 } = { b: undefined }; // b is 2
const { c = 2 } = { c: null }; // c is null
```
The default value can be any expression. It will only be evaluated when necessary.
```js
const { b = console.log("hey") } = { b: 2 };
// Does not log anything, because `b` is defined and there's no need
// to evaluate the default value.
```
### Rest property
You can end a destructuring pattern with a rest property `...rest`. This pattern will store all remaining properties of the object or array into a new object or array.
```js
const { a, ...others } = { a: 1, b: 2, c: 3 };
console.log(others); // { b: 2, c: 3 }
const [first, ...others2] = [1, 2, 3];
console.log(others2); // [2, 3]
```
The rest property must be the last in the pattern, and must not have a trailing comma.
```js-nolint example-bad
const [a, ...b,] = [1, 2, 3];
// SyntaxError: rest element may not have a trailing comma
// Always consider using rest operator as the last element
```
## Examples
### Array destructuring
#### Basic variable assignment
```js
const foo = ["one", "two", "three"];
const [red, yellow, green] = foo;
console.log(red); // "one"
console.log(yellow); // "two"
console.log(green); // "three"
```
#### Destructuring with more elements than the source
In an array destructuring from an array of length _N_ specified on the right-hand side of the assignment, if the number of variables specified on the left-hand side of the assignment is greater than _N_, only the first _N_ variables are assigned values. The values of the remaining variables will be undefined.
```js
const foo = ["one", "two"];
const [red, yellow, green, blue] = foo;
console.log(red); // "one"
console.log(yellow); // "two"
console.log(green); // undefined
console.log(blue); // undefined
```
#### Swapping variables
Two variables values can be swapped in one destructuring expression.
Without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the [XOR-swap trick](https://en.wikipedia.org/wiki/XOR_swap_algorithm)).
```js
let a = 1;
let b = 3;
[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1
const arr = [1, 2, 3];
[arr[2], arr[1]] = [arr[1], arr[2]];
console.log(arr); // [1, 3, 2]
```
#### Parsing an array returned from a function
It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise.
In this example, `f()` returns the values `[1, 2]` as its output, which can be parsed in a single line with destructuring.
```js
function f() {
return [1, 2];
}
const [a, b] = f();
console.log(a); // 1
console.log(b); // 2
```
#### Ignoring some returned values
You can ignore return values that you're not interested in:
```js
function f() {
return [1, 2, 3];
}
const [a, , b] = f();
console.log(a); // 1
console.log(b); // 3
const [c] = f();
console.log(c); // 1
```
You can also ignore all returned values:
```js
[, ,] = f();
```
#### Using a binding pattern as the rest property
The rest property of array destructuring assignment can be another array or object binding pattern. The inner destructuring destructures from the array created after collecting the rest elements, so you cannot access any properties present on the original iterable in this way.
```js
const [a, b, ...{ length }] = [1, 2, 3];
console.log(a, b, length); // 1 2 1
```
```js
const [a, b, ...[c, d]] = [1, 2, 3, 4];
console.log(a, b, c, d); // 1 2 3 4
```
These binding patterns can even be nested, as long as each rest property is the last in the list.
```js
const [a, b, ...[c, d, ...[e, f]]] = [1, 2, 3, 4, 5, 6];
console.log(a, b, c, d, e, f); // 1 2 3 4 5 6
```
On the other hand, object destructuring can only have an identifier as the rest property.
```js-nolint example-bad
const { a, ...{ b } } = { a: 1, b: 2 };
// SyntaxError: `...` must be followed by an identifier in declaration contexts
let a, b;
({ a, ...{ b } } = { a: 1, b: 2 });
// SyntaxError: `...` must be followed by an assignable reference in assignment contexts
```
#### Unpacking values from a regular expression match
When the regular expression [`exec()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if it is not needed.
```js
function parseProtocol(url) {
const parsedURL = /^(\w+):\/\/([^/]+)\/(.*)$/.exec(url);
if (!parsedURL) {
return false;
}
console.log(parsedURL);
// ["https://developer.mozilla.org/en-US/docs/Web/JavaScript",
// "https", "developer.mozilla.org", "en-US/docs/Web/JavaScript"]
const [, protocol, fullhost, fullpath] = parsedURL;
return protocol;
}
console.log(
parseProtocol("https://developer.mozilla.org/en-US/docs/Web/JavaScript"),
);
// "https"
```
#### Using array destructuring on any iterable
Array destructuring calls the [iterable protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of the right-hand side. Therefore, any iterable, not necessarily arrays, can be destructured.
```js
const [a, b] = new Map([
[1, 2],
[3, 4],
]);
console.log(a, b); // [1, 2] [3, 4]
```
Non-iterables cannot be destructured as arrays.
```js example-bad
const obj = { 0: "a", 1: "b", length: 2 };
const [a, b] = obj;
// TypeError: obj is not iterable
```
Iterables are only iterated until all bindings are assigned.
```js
const obj = {
*[Symbol.iterator]() {
for (const v of [0, 1, 2, 3]) {
console.log(v);
yield v;
}
},
};
const [a, b] = obj; // Only logs 0 and 1
```
The rest binding is eagerly evaluated and creates a new array, instead of using the old iterable.
```js
const obj = {
*[Symbol.iterator]() {
for (const v of [0, 1, 2, 3]) {
console.log(v);
yield v;
}
},
};
const [a, b, ...rest] = obj; // Logs 0 1 2 3
console.log(rest); // [2, 3] (an array)
```
### Object destructuring
#### Basic assignment
```js
const user = {
id: 42,
isVerified: true,
};
const { id, isVerified } = user;
console.log(id); // 42
console.log(isVerified); // true
```
#### Assigning to new variable names
A property can be unpacked from an object and assigned to a variable with a different name than the object property.
```js
const o = { p: 42, q: true };
const { p: foo, q: bar } = o;
console.log(foo); // 42
console.log(bar); // true
```
Here, for example, `const { p: foo } = o` takes from the object `o` the property named `p` and assigns it to a local variable named `foo`.
#### Assigning to new variable names and providing default values
A property can be both
- Unpacked from an object and assigned to a variable with a different name.
- Assigned a default value in case the unpacked value is `undefined`.
```js
const { a: aa = 10, b: bb = 5 } = { a: 3 };
console.log(aa); // 3
console.log(bb); // 5
```
#### Unpacking properties from objects passed as a function parameter
Objects passed into function parameters can also be unpacked into variables, which may then be accessed within the function body.
As for object assignment, the destructuring syntax allows for the new variable to have the same name or a different name than the original property, and to assign default values for the case when the original object does not define the property.
Consider this object, which contains information about a user.
```js
const user = {
id: 42,
displayName: "jdoe",
fullName: {
firstName: "Jane",
lastName: "Doe",
},
};
```
Here we show how to unpack a property of the passed object into a variable with the same name.
The parameter value `{ id }` indicates that the `id` property of the object passed to the function should be unpacked into a variable with the same name, which can then be used within the function.
```js
function userId({ id }) {
return id;
}
console.log(userId(user)); // 42
```
You can define the name of the unpacked variable.
Here we unpack the property named `displayName`, and rename it to `dname` for use within the function body.
```js
function userDisplayName({ displayName: dname }) {
return dname;
}
console.log(userDisplayName(user)); // "jdoe"
```
Nested objects can also be unpacked.
The example below shows the property `fullname.firstName` being unpacked into a variable called `name`.
```js
function whois({ displayName, fullName: { firstName: name } }) {
return `${displayName} is ${name}`;
}
console.log(whois(user)); // "jdoe is Jane"
```
#### Setting a function parameter's default value
Default values can be specified using `=`, and will be used as variable values if a specified property does not exist in the passed object.
Below we show a function where the default size is `'big'`, default co-ordinates are `x: 0, y: 0` and default radius is 25.
```js
function drawChart({
size = "big",
coords = { x: 0, y: 0 },
radius = 25,
} = {}) {
console.log(size, coords, radius);
// do some chart drawing
}
drawChart({
coords: { x: 18, y: 30 },
radius: 30,
});
```
In the function signature for `drawChart` above, the destructured left-hand side has a default value of an empty object `= {}`.
You could have also written the function without that default. However, if you leave out that default value, the function will look for at least one argument to be supplied when invoked, whereas in its current form, you can call `drawChart()` without supplying any parameters. Otherwise, you need to at least supply an empty object literal.
For more information, see [Default parameters > Destructured parameter with default value assignment](/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters#destructured_parameter_with_default_value_assignment).
#### Nested object and array destructuring
```js
const metadata = {
title: "Scratchpad",
translations: [
{
locale: "de",
localizationTags: [],
lastEdit: "2014-04-14T08:43:37",
url: "/de/docs/Tools/Scratchpad",
title: "JavaScript-Umgebung",
},
],
url: "/en-US/docs/Tools/Scratchpad",
};
const {
title: englishTitle, // rename
translations: [
{
title: localeTitle, // rename
},
],
} = metadata;
console.log(englishTitle); // "Scratchpad"
console.log(localeTitle); // "JavaScript-Umgebung"
```
#### For of iteration and destructuring
```js
const people = [
{
name: "Mike Smith",
family: {
mother: "Jane Smith",
father: "Harry Smith",
sister: "Samantha Smith",
},
age: 35,
},
{
name: "Tom Jones",
family: {
mother: "Norah Jones",
father: "Richard Jones",
brother: "Howard Jones",
},
age: 25,
},
];
for (const {
name: n,
family: { father: f },
} of people) {
console.log(`Name: ${n}, Father: ${f}`);
}
// "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"
```
#### Computed object property names and destructuring
Computed property names, like on [object literals](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names), can be used with destructuring.
```js
const key = "z";
const { [key]: foo } = { z: "bar" };
console.log(foo); // "bar"
```
#### Invalid JavaScript identifier as a property name
Destructuring can be used with property names that are not valid JavaScript {{Glossary("Identifier", "identifiers")}} by providing an alternative identifier that is valid.
```js
const foo = { "fizz-buzz": true };
const { "fizz-buzz": fizzBuzz } = foo;
console.log(fizzBuzz); // true
```
### Destructuring primitive values
Object destructuring is almost equivalent to [property accessing](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors). This means if you try to destruct a primitive value, the value will get wrapped into the corresponding wrapper object and the property is accessed on the wrapper object.
```js
const { a, toFixed } = 1;
console.log(a, toFixed); // undefined Ζ toFixed() { [native code] }
```
Same as accessing properties, destructuring `null` or `undefined` throws a {{jsxref("TypeError")}}.
```js example-bad
const { a } = undefined; // TypeError: Cannot destructure property 'a' of 'undefined' as it is undefined.
const { b } = null; // TypeError: Cannot destructure property 'b' of 'null' as it is null.
```
This happens even when the pattern is empty.
```js example-bad
const {} = null; // TypeError: Cannot destructure 'null' as it is null.
```
#### Combined array and object destructuring
Array and object destructuring can be combined. Say you want the third element in the array `props` below, and then you want the `name` property in the object, you can do the following:
```js
const props = [
{ id: 1, name: "Fizz" },
{ id: 2, name: "Buzz" },
{ id: 3, name: "FizzBuzz" },
];
const [, , { name }] = props;
console.log(name); // "FizzBuzz"
```
#### The prototype chain is looked up when the object is deconstructed
When deconstructing an object, if a property is not accessed in itself, it will continue to look up along the prototype chain.
```js
const obj = {
self: "123",
__proto__: {
prot: "456",
},
};
const { self, prot } = obj;
console.log(self); // "123"
console.log(prot); // "456"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Assignment operators](/en-US/docs/Web/JavaScript/Reference/Operators#assignment_operators)
- [ES6 in Depth: Destructuring](https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/) on hacks.mozilla.org (2015)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/object_initializer/index.md | ---
title: Object initializer
slug: Web/JavaScript/Reference/Operators/Object_initializer
page-type: javascript-language-feature
browser-compat: javascript.operators.object_initializer
---
{{jsSidebar("Operators")}}
An **object initializer** is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces (`{}`). Objects can also be initialized using [`Object.create()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create) or [by invoking a constructor function](/en-US/docs/Web/JavaScript/Guide/Working_with_objects#using_a_constructor_function) with the [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new) operator.
{{EmbedInteractiveExample("pages/js/expressions-objectinitializer.html", "taller")}}
## Syntax
```js-nolint
o = {
a: "foo",
b: 42,
c: {},
1: "number literal property",
"foo:bar": "string literal property",
shorthandProperty,
method(parameters) {
// β¦
},
get property() {},
set property(value) {},
[expression]: "computed property",
__proto__: prototype,
...spreadProperty,
};
```
## Description
An object initializer is an expression that describes the initialization of an {{jsxref("Object")}}. Objects consist of _properties_, which are used to describe an object. The values of object properties can either contain [primitive](/en-US/docs/Glossary/Primitive) data types or other objects.
### Object literal syntax vs. JSON
The object literal syntax is not the same as the **J**ava**S**cript **O**bject **N**otation ([JSON](/en-US/docs/Glossary/JSON)). Although they look similar, there are differences between them:
- JSON _only_ permits property definition using the `"property": value` syntax. The property name must be double-quoted, and the definition cannot be a shorthand. Computed property names are not allowed either.
- JSON object property values can only be strings, numbers, `true`, `false`, `null`, arrays, or another JSON object. This means JSON cannot express methods or non-plain objects like [`Date`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) or [`RegExp`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp).
- In JSON, `"__proto__"` is a normal property key. In an object literal, it [sets the object's prototype](#prototype_setter).
JSON is a _strict subset_ of the object literal syntax, meaning that every valid JSON text can be parsed as an object literal, and would likely not cause syntax errors. The only exception is that the object literal syntax prohibits duplicate `__proto__` keys, which does not apply to [`JSON.parse()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse). The latter treats `__proto__` like a normal property and takes the last occurrence as the property's value. The only time when the object value they represent (a.k.a. their semantic) differ is also when the source contains the `__proto__` key β for object literals, it sets the object's prototype; for JSON, it's a normal property.
```js
console.log(JSON.parse('{ "__proto__": 0, "__proto__": 1 }')); // {__proto__: 1}
console.log({ "__proto__": 0, "__proto__": 1 }); // SyntaxError: Duplicate __proto__ fields are not allowed in object literals
console.log(JSON.parse('{ "__proto__": {} }')); // { __proto__: {} }
console.log({ "__proto__": {} }); // {} (with {} as prototype)
```
## Examples
### Creating objects
An empty object with no properties can be created like this:
```js
const object = {};
```
However, the advantage of the _literal_ or _initializer_ notation is, that you are able to quickly create objects with properties inside the curly braces. You notate a list of `key: value` pairs delimited by commas.
The following code creates an object with three properties and the keys are `"foo"`, `"age"` and `"baz"`. The values of these keys are a string `"bar"`, the number `42`, and another object.
```js
const object = {
foo: "bar",
age: 42,
baz: { myProp: 12 },
};
```
### Accessing properties
Once you have created an object, you might want to read or change them. Object properties can be accessed by using the dot notation or the bracket notation. (See [property accessors](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors) for detailed information.)
```js
object.foo; // "bar"
object["age"]; // 42
object.baz; // {myProp: 12}
object.baz.myProp; //12
```
### Property definitions
We have already learned how to notate properties using the initializer syntax. Oftentimes, there are variables in your code that you would like to put into an object. You will see code like this:
```js
const a = "foo";
const b = 42;
const c = {};
const o = {
a: a,
b: b,
c: c,
};
```
There is a shorter notation available to achieve the same:
```js
const a = "foo";
const b = 42;
const c = {};
// Shorthand property names
const o = { a, b, c };
// In other words,
console.log(o.a === { a }.a); // true
```
#### Duplicate property names
When using the same name for your properties, the second property will overwrite the first.
```js
const a = { x: 1, x: 2 };
console.log(a); // {x: 2}
```
After ES2015, duplicate property names are allowed everywhere, including [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode#duplicate_property_names). You can also have duplicate property names in [classes](/en-US/docs/Web/JavaScript/Reference/Classes). The only exception is [private properties](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties), which must be unique in the class body.
### Method definitions
A property of an object can also refer to a [function](/en-US/docs/Web/JavaScript/Reference/Functions) or a [getter](/en-US/docs/Web/JavaScript/Reference/Functions/get) or [setter](/en-US/docs/Web/JavaScript/Reference/Functions/set) method.
```js
const o = {
property: function (parameters) {},
get property() {},
set property(value) {},
};
```
A shorthand notation is available, so that the keyword `function` is no longer necessary.
```js
// Shorthand method names
const o = {
property(parameters) {},
};
```
There is also a way to concisely define generator methods.
```js
const o = {
*generator() {
// β¦
},
};
```
Which is equivalent to this ES5-like notation (but note that ECMAScript 5 has no generators):
```js
const o = {
generator: function* () {
// β¦
},
};
```
For more information and examples about methods, see [method definitions](/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions).
### Computed property names
The object initializer syntax also supports computed property names. That allows you to put an expression in square brackets `[]`, that will be computed and used as the property name. This is reminiscent of the bracket notation of the [property accessor](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors) syntax, which you may have used to read and set properties already.
Now you can use a similar syntax in object literals, too:
```js
// Computed property names
let i = 0;
const a = {
[`foo${++i}`]: i,
[`foo${++i}`]: i,
[`foo${++i}`]: i,
};
console.log(a.foo1); // 1
console.log(a.foo2); // 2
console.log(a.foo3); // 3
const items = ["A", "B", "C"];
const obj = {
[items]: "Hello",
};
console.log(obj); // A,B,C: "Hello"
console.log(obj["A,B,C"]); // "Hello"
const param = "size";
const config = {
[param]: 12,
[`mobile${param.charAt(0).toUpperCase()}${param.slice(1)}`]: 4,
};
console.log(config); // {size: 12, mobileSize: 4}
```
### Spread properties
Object literals support the [spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). It copies own enumerable properties from a provided object onto a new object.
Shallow-cloning (excluding `prototype`) or merging objects is now possible using a shorter syntax than {{jsxref("Object.assign()")}}.
```js
const obj1 = { foo: "bar", x: 42 };
const obj2 = { foo: "baz", y: 13 };
const clonedObj = { ...obj1 };
// { foo: "bar", x: 42 }
const mergedObj = { ...obj1, ...obj2 };
// { foo: "baz", x: 42, y: 13 }
```
> **Warning:** Note that {{jsxref("Object.assign()")}} triggers [setters](/en-US/docs/Web/JavaScript/Reference/Functions/set), whereas the spread syntax doesn't!
### Prototype setter
A property definition of the form `__proto__: value` or `"__proto__": value` does not create a property with the name `__proto__`. Instead, if the provided value is an object or [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null), it points the `[[Prototype]]` of the created object to that value. (If the value is not an object or `null`, the object is not changed.)
Note that the `__proto__` key is standardized syntax, in contrast to the non-standard and non-performant [`Object.prototype.__proto__`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto) accessors. It sets the `[[Prototype]]` during object creation, similar to {{jsxref("Object.create")}} β instead of mutating the prototype chain.
```js-nolint
const obj1 = {};
console.log(Object.getPrototypeOf(obj1) === Object.prototype); // true
const obj2 = { __proto__: null };
console.log(Object.getPrototypeOf(obj2)); // null
const protoObj = {};
const obj3 = { "__proto__": protoObj };
console.log(Object.getPrototypeOf(obj3) === protoObj); // true
const obj4 = { __proto__: "not an object or null" };
console.log(Object.getPrototypeOf(obj4) === Object.prototype); // true
console.log(Object.hasOwn(obj4, "__proto__")); // false
```
Only a single prototype setter is permitted in an object literal. Multiple prototype setters are a syntax error.
Property definitions that do not use "colon" notation are not prototype setters. They are property definitions that behave identically to similar definitions using any other name.
```js
const __proto__ = "variable";
const obj1 = { __proto__ };
console.log(Object.getPrototypeOf(obj1) === Object.prototype); // true
console.log(Object.hasOwn(obj1, "__proto__")); // true
console.log(obj1.__proto__); // "variable"
const obj2 = { __proto__() { return "hello"; } };
console.log(obj2.__proto__()); // "hello"
const obj3 = { ["__proto__"]: 17 };
console.log(obj3.__proto__); // 17
// Mixing prototype setter with normal own properties with "__proto__" key
const obj4 = { ["__proto__"]: 17, __proto__: {} }; // {__proto__: 17} (with {} as prototype)
const obj5 = {
["__proto__"]: 17,
__proto__: {},
__proto__: null, // SyntaxError: Duplicate __proto__ fields are not allowed in object literals
};
const obj6 = {
["__proto__"]: 17,
["__proto__"]: "hello",
__proto__: null,
}; // {__proto__: "hello"} (with null as prototype)
const obj7 = {
["__proto__"]: 17,
__proto__,
__proto__: null,
}; // {__proto__: "variable"} (with null as prototype)
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Property accessors](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors)
- [`get`](/en-US/docs/Web/JavaScript/Reference/Functions/get)
- [`set`](/en-US/docs/Web/JavaScript/Reference/Functions/set)
- [Method definitions](/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions)
- [Lexical grammar](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/bitwise_or/index.md | ---
title: Bitwise OR (|)
slug: Web/JavaScript/Reference/Operators/Bitwise_OR
page-type: javascript-operator
browser-compat: javascript.operators.bitwise_or
---
{{jsSidebar("Operators")}}
The **bitwise OR (`|`)** operator returns a number or BigInt whose binary representation has a `1` in each bit position for which the corresponding bits of either or both operands are `1`.
{{EmbedInteractiveExample("pages/js/expressions-bitwise-or.html", "shorter")}}
## Syntax
```js-nolint
x | y
```
## Description
The `|` operator is overloaded for two types of operands: number and [BigInt](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt). For numbers, the operator returns a 32-bit integer. For BigInts, the operator returns a BigInt. It first [coerces both operands to numeric values](/en-US/docs/Web/JavaScript/Data_structures#numeric_coercion) and tests the types of them. It performs BigInt OR if both operands become BigInts; otherwise, it converts both operands to [32-bit integers](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#fixed-width_number_conversion) and performs number bitwise OR. A {{jsxref("TypeError")}} is thrown if one operand becomes a BigInt but the other becomes a number.
The operator operates on the operands' bit representations in [two's complement](https://en.wikipedia.org/wiki/Two's_complement). Each bit in the first operand is paired with the corresponding bit in the second operand: _first bit_ to _first bit_, _second bit_ to _second bit_, and so on. The operator is applied to each pair of bits, and the result is constructed bitwise.
The truth table for the OR operation is:
| x | y | x OR y |
| --- | --- | ------ |
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 1 |
```plain
9 (base 10) = 00000000000000000000000000001001 (base 2)
14 (base 10) = 00000000000000000000000000001110 (base 2)
--------------------------------
14 | 9 (base 10) = 00000000000000000000000000001111 (base 2) = 15 (base 10)
```
Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32-bit integer:
```plain
Before: 11100110111110100000000000000110000000000001
After: 10100000000000000110000000000001
```
For BigInts, there's no truncation. Conceptually, understand positive BigInts as having an infinite number of leading `0` bits, and negative BigInts having an infinite number of leading `1` bits.
Bitwise ORing any number `x` with `0` returns `x` converted to a 32-bit integer. Do not use `| 0` to truncate numbers to integers; use [`Math.trunc()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#using_bitwise_no-ops_to_truncate_numbers) instead.
## Examples
### Using bitwise OR
```js
// 9 (00000000000000000000000000001001)
// 14 (00000000000000000000000000001110)
14 | 9;
// 15 (00000000000000000000000000001111)
14n | 9n; // 15n
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Bitwise operators in the JS guide](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#bitwise_operators)
- [Bitwise OR assignment (`|=`)](/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR_assignment)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/exponentiation_assignment/index.md | ---
title: Exponentiation assignment (**=)
slug: Web/JavaScript/Reference/Operators/Exponentiation_assignment
page-type: javascript-operator
browser-compat: javascript.operators.exponentiation_assignment
---
{{jsSidebar("Operators")}}
The **exponentiation assignment (`**=`)\*\* operator performs [exponentiation](/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation) on the two operands and assigns the result to the left operand.
{{EmbedInteractiveExample("pages/js/expressions-exponentiation-assignment.html")}}
## Syntax
```js-nolint
x **= y
```
## Description
`x **= y` is equivalent to `x = x ** y`, except that the expression `x` is only evaluated once.
## Examples
### Using exponentiation assignment
```js
let bar = 5;
bar **= 2; // 25
bar **= "foo"; // NaN
let foo = 3n;
foo **= 2n; // 9n
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Assignment operators in the JS guide](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#assignment_operators)
- [Exponentiation (`**`)](/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/less_than_or_equal/index.md | ---
title: Less than or equal (<=)
slug: Web/JavaScript/Reference/Operators/Less_than_or_equal
page-type: javascript-operator
browser-compat: javascript.operators.less_than_or_equal
---
{{jsSidebar("Operators")}}
The **less than or equal (`<=`)** operator returns `true` if the left operand is less than or equal to the right operand, and `false` otherwise.
{{EmbedInteractiveExample("pages/js/expressions-less-than-or-equal.html")}}
## Syntax
```js-nolint
x <= y
```
## Description
The operands are compared using the same algorithm as the [Less than](/en-US/docs/Web/JavaScript/Reference/Operators/Less_than) operator, with the operands swapped and the result negated. `x <= y` is generally equivalent to `!(y < x)`, except for two cases where `x <= y` and `x > y` are both `false`:
- If one of the operands gets converted to a BigInt, while the other gets converted to a string that cannot be converted to a BigInt value (it throws a [syntax error](/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_BigInt_syntax) when passed to [`BigInt()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/BigInt)).
- If one of the operands gets converted to `NaN`. (For example, strings that cannot be converted to numbers, or `undefined`.)
In addition, `x <= y` coerces `x` to a primitive before `y`, while `y < x` coerces `y` to a primitive before `x`. Because coercion may have side effects, the order of the operands may matter.
`x <= y` is generally equivalent to `x < y || x == y`, except for a few cases:
- When one of `x` or `y` is `null`, and the other is something that's not `null` and becomes 0 when [coerced to numeric](/en-US/docs/Web/JavaScript/Data_structures#numeric_coercion) (including `0`, `0n`, `false`, `""`, `"0"`, `new Date(0)`, etc.): `x <= y` is `true`, while `x < y || x == y` is `false`.
- When one of `x` or `y` is `undefined`, and the other is one of `null` or `undefined`: `x <= y` is `false`, while `x == y` is `true`.
- When `x` and `y` are the same object that becomes `NaN` after the first step of [Less than](/en-US/docs/Web/JavaScript/Reference/Operators/Less_than) (such as `new Date(NaN)`): `x <= y` is `false`, while `x == y` is `true`.
- When `x` and `y` are different objects that become the same value after the first step of [Less than](/en-US/docs/Web/JavaScript/Reference/Operators/Less_than): `x <= y` is `true`, while `x < y || x == y` is `false`.
## Examples
### String to string comparison
```js
"a" <= "b"; // true
"a" <= "a"; // true
"a" <= "3"; // false
```
### String to number comparison
```js
"5" <= 3; // false
"3" <= 3; // true
"3" <= 5; // true
"hello" <= 5; // false
5 <= "hello"; // false
```
### Number to Number comparison
```js
5 <= 3; // false
3 <= 3; // true
3 <= 5; // true
```
### Number to BigInt comparison
```js
5n <= 3; // false
3 <= 3n; // true
3 <= 5n; // true
```
### Comparing Boolean, null, undefined, NaN
```js
true <= false; // false
true <= true; // true
false <= true; // true
true <= 0; // false
true <= 1; // true
null <= 0; // true
1 <= null; // false
undefined <= 3; // false
3 <= undefined; // false
3 <= NaN; // false
NaN <= 3; // false
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Greater than (`>`)](/en-US/docs/Web/JavaScript/Reference/Operators/Greater_than)
- [Greater than or equal (`>=`)](/en-US/docs/Web/JavaScript/Reference/Operators/Greater_than_or_equal)
- [Less than (`<`)](/en-US/docs/Web/JavaScript/Reference/Operators/Less_than)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/multiplication_assignment/index.md | ---
title: Multiplication assignment (*=)
slug: Web/JavaScript/Reference/Operators/Multiplication_assignment
page-type: javascript-operator
browser-compat: javascript.operators.multiplication_assignment
---
{{jsSidebar("Operators")}}
The **multiplication assignment (`*=`)** operator performs [multiplication](/en-US/docs/Web/JavaScript/Reference/Operators/Multiplication) on the two operands and assigns the result to the left operand.
{{EmbedInteractiveExample("pages/js/expressions-multiplication-assignment.html")}}
## Syntax
```js-nolint
x *= y
```
## Description
`x *= y` is equivalent to `x = x * y`, except that the expression `x` is only evaluated once.
## Examples
### Using multiplication assignment
```js
let bar = 5;
bar *= 2; // 10
bar *= "foo"; // NaN
let foo = 3n;
foo *= 2n; // 6n
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Assignment operators in the JS guide](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#assignment_operators)
- [Multiplication (`*`)](/en-US/docs/Web/JavaScript/Reference/Operators/Multiplication)
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.