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/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/subtraction_assignment/index.md | ---
title: Subtraction assignment (-=)
slug: Web/JavaScript/Reference/Operators/Subtraction_assignment
page-type: javascript-operator
browser-compat: javascript.operators.subtraction_assignment
---
{{jsSidebar("Operators")}}
The **subtraction assignment (`-=`)** operator performs [subtraction](/en-US/docs/Web/JavaScript/Reference/Operators/Subtraction) on the two operands and assigns the result to the left operand.
{{EmbedInteractiveExample("pages/js/expressions-subtraction-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 subtraction assignment
```js
let bar = 5;
bar -= 2; // 3
bar -= "foo"; // NaN
let foo = 3n;
foo -= 2n; // 1n
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Assignment operators in the JS guide](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#assignment_operators)
- [Subtraction (`-`)](/en-US/docs/Web/JavaScript/Reference/Operators/Subtraction)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/optional_chaining/index.md | ---
title: Optional chaining (?.)
slug: Web/JavaScript/Reference/Operators/Optional_chaining
page-type: javascript-operator
browser-compat: javascript.operators.optional_chaining
---
{{jsSidebar("Operators")}}
The **optional chaining (`?.`)** operator accesses an object's property or calls a function. If the object accessed or function called using this operator is {{jsxref("undefined")}} or [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null), the expression short circuits and evaluates to {{jsxref("undefined")}} instead of throwing an error.
{{EmbedInteractiveExample("pages/js/expressions-optionalchainingoperator.html", "taller")}}
## Syntax
```js-nolint
obj.val?.prop
obj.val?.[expr]
obj.func?.(args)
```
## Description
The `?.` operator is like the `.` chaining operator, except that 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 {{jsxref("undefined")}}), the expression short-circuits with a return value of `undefined`. When used with function calls, it returns `undefined` if the given function does not exist.
This results in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing. It can also be helpful while exploring the content of an object when there's no known guarantee as to which properties are required.
For example, consider an object `obj` which has a nested structure. Without
optional chaining, looking up a deeply-nested subproperty requires validating the
references in between, such as:
```js
const nestedProp = obj.first && obj.first.second;
```
The value of `obj.first` is confirmed to be non-`null` (and
non-`undefined`) before accessing the value of
`obj.first.second`. This prevents the error that would occur if you accessed
`obj.first.second` directly without testing `obj.first`.
This is an idiomatic pattern in JavaScript, but it gets verbose when the chain is long, and it's not safe. For example, if `obj.first` is a {{Glossary("Falsy")}} value that's not `null` or `undefined`, such as `0`, it would still short-circuit and make `nestedProp` become `0`, which may not be desirable.
With the optional chaining operator (`?.`), however, you don't have to
explicitly test and short-circuit based on the state of `obj.first` before
trying to access `obj.first.second`:
```js
const nestedProp = obj.first?.second;
```
By using the `?.` operator instead of just `.`, JavaScript knows
to implicitly check to be sure `obj.first` is not `null` or
`undefined` before attempting to access `obj.first.second`. If
`obj.first` is `null` or `undefined`, the expression
automatically short-circuits, returning `undefined`.
This is equivalent to the following, except that the temporary variable is in fact not
created:
```js
const temp = obj.first;
const nestedProp =
temp === null || temp === undefined ? undefined : temp.second;
```
Optional chaining cannot be used on a non-declared root object, but can be used with a root object with value `undefined`.
```js example-bad
undeclaredVar?.prop; // ReferenceError: undeclaredVar is not defined
```
### Optional chaining with function calls
You can use optional chaining when attempting to call a method which may not exist.
This can be helpful, for example, when using an API in which a method might be
unavailable, either due to the age of the implementation or because of a feature which
isn't available on the user's device.
Using optional chaining with function calls causes the expression to automatically
return `undefined` instead of throwing an exception if the method isn't
found:
```js
const result = someInterface.customMethod?.();
```
However, if there is a property with such a name which is not a function, using `?.` will still raise a {{jsxref("TypeError")}} exception "someInterface.customMethod is not a function".
> **Note:** If `someInterface` itself is `null` or
> `undefined`, a {{jsxref("TypeError")}} exception will still be
> raised ("someInterface is null"). If you expect that
> `someInterface` itself may be `null` or `undefined`,
> you have to use `?.` at this position as
> well: `someInterface?.customMethod?.()`.
`eval?.()` is the shortest way to enter [_indirect eval_](/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#direct_and_indirect_eval) mode.
### Optional chaining with expressions
You can also use the optional chaining operator with [bracket notation](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#bracket_notation), which allows passing an expression as the property name:
```js
const nestedProp = obj?.["prop" + "Name"];
```
This is particularly useful for arrays, since array indices must be accessed with square brackets.
```js
function printMagicIndex(arr) {
console.log(arr?.[42]);
}
printMagicIndex([0, 1, 2, 3, 4, 5]); // undefined
printMagicIndex(); // undefined; if not using ?., this would throw an error: "Cannot read properties of undefined (reading '42')"
```
### Optional chaining not valid on the left-hand side of an assignment
It is invalid to try to assign to the result of an optional chaining expression:
```js-nolint example-bad
const object = {};
object?.property = 1; // SyntaxError: Invalid left-hand side in assignment
```
### Short-circuiting
When using optional chaining with expressions, if the left operand is `null` or `undefined`, the expression will not be evaluated. For instance:
```js
const potentiallyNullObj = null;
let x = 0;
const prop = potentiallyNullObj?.[x++];
console.log(x); // 0 as x was not incremented
```
Subsequent property accesses will not be evaluated either.
```js
const potentiallyNullObj = null;
const prop = potentiallyNullObj?.a.b;
// This does not throw, because evaluation has already stopped at
// the first optional chain
```
This is equivalent to:
```js
const potentiallyNullObj = null;
const prop =
potentiallyNullObj === null || potentiallyNullObj === undefined
? undefined
: potentiallyNullObj.a.b;
```
However, this short-circuiting behavior only happens along one continuous "chain" of property accesses. If you [group](/en-US/docs/Web/JavaScript/Reference/Operators/Grouping) one part of the chain, then subsequent property accesses will still be evaluated.
```js
const potentiallyNullObj = null;
const prop = (potentiallyNullObj?.a).b;
// TypeError: Cannot read properties of undefined (reading 'b')
```
This is equivalent to:
```js
const potentiallyNullObj = null;
const temp = potentiallyNullObj?.a;
const prop = temp.b;
```
Except the `temp` variable isn't created.
## Examples
### Basic example
This example looks for the value of the `name` property for the member
`bar` in a map when there is no such member. The result is therefore
`undefined`.
```js
const myMap = new Map();
myMap.set("foo", { name: "baz", desc: "inga" });
const nameBar = myMap.get("bar")?.name;
```
### Dealing with optional callbacks or event handlers
If you use callbacks or fetch methods from an object with
[a destructuring assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#object_destructuring), you may have non-existent values that you cannot call as
functions unless you have tested their existence. Using `?.`, you can avoid this extra test:
```js
// Code written without optional chaining
function doSomething(onContent, onError) {
try {
// Do something with the data
} catch (err) {
// Testing if onError really exists
if (onError) {
onError(err.message);
}
}
}
```
```js
// Using optional chaining with function calls
function doSomething(onContent, onError) {
try {
// Do something with the data
} catch (err) {
onError?.(err.message); // No exception if onError is undefined
}
}
```
### Stacking the optional chaining operator
With nested structures, it is possible to use optional chaining multiple times:
```js
const customer = {
name: "Carl",
details: {
age: 82,
location: "Paradise Falls", // Detailed address is unknown
},
};
const customerCity = customer.details?.address?.city;
// This also works with optional chaining function call
const customerName = customer.name?.getName?.(); // Method does not exist, customerName is undefined
```
### Combining with the nullish coalescing operator
The [nullish coalescing operator](/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing) may be used after optional chaining in order to build a default value when none was found:
```js
function printCustomerCity(customer) {
const customerCity = customer?.city ?? "Unknown city";
console.log(customerCity);
}
printCustomerCity({
name: "Nathan",
city: "Paris",
}); // "Paris"
printCustomerCity({
name: "Carl",
details: { age: 82 },
}); // "Unknown city"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Nullish coalescing operator (`??`)](/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/new/index.md | ---
title: new
slug: Web/JavaScript/Reference/Operators/new
page-type: javascript-operator
browser-compat: javascript.operators.new
---
{{jsSidebar("Operators")}}
The **`new`** operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.
{{EmbedInteractiveExample("pages/js/expressions-newoperator.html")}}
## Syntax
```js-nolint
new constructor
new constructor()
new constructor(arg1)
new constructor(arg1, arg2)
new constructor(arg1, arg2, /* β¦, */ argN)
```
### Parameters
- `constructor`
- : A class or function that specifies the type of the object instance.
- `arg1`, `arg2`, β¦, `argN`
- : A list of values that the `constructor` will be called with. `new Foo` is equivalent to `new Foo()`, i.e. if no argument list is specified, `Foo` is called without arguments.
## Description
When a function is called with the **`new`** keyword, the function will be used as a constructor. `new` will do the following things:
1. Creates a blank, plain JavaScript object. For convenience, let's call it `newInstance`.
2. Points `newInstance`'s [[Prototype]] to the constructor function's `prototype` property, if the `prototype` is an {{jsxref("Object")}}. Otherwise, `newInstance` stays as a plain object with `Object.prototype` as its [[Prototype]].
> **Note:** Properties/objects added to the constructor function's `prototype` property are therefore accessible to all instances created from the constructor function.
3. Executes the constructor function with the given arguments, binding `newInstance` as the [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this) context (i.e. all references to `this` in the constructor function now refer to `newInstance`).
4. If the constructor function returns a [non-primitive](/en-US/docs/Web/JavaScript/Data_structures#primitive_values), this return value becomes the result of the whole `new` expression. Otherwise, if the constructor function doesn't return anything or returns a primitive, `newInstance` is returned instead. (Normally constructors don't return a value, but they can choose to do so to override the normal object creation process.)
[Classes](/en-US/docs/Web/JavaScript/Reference/Classes) can only be instantiated with the `new` operator β attempting to call a class without `new` will throw a `TypeError`.
Creating an object with a user-defined constructor function requires two steps:
1. Define the object type by writing a function that specifies its name and properties.
For example, a constructor function to create an object `Foo` might look like this:
```js
function Foo(bar1, bar2) {
this.bar1 = bar1;
this.bar2 = bar2;
}
```
2. Create an instance of the object with `new`.
```js
const myFoo = new Foo("Bar 1", 2021);
```
> **Note:** An object can have a property that is itself another object. See the examples below.
You can always add a property to a previously defined object instance. For example, the statement `car1.color = "black"` adds a property `color` to `car1`, and assigns it a value of `"black"`.
However, this does not affect any other objects. To add the new property to all objects of the same type, you must add the property to the constructor's `prototype` property. This defines a property that is shared by all objects created with that function, rather than by just one instance of the object type. The following code adds a `color` property with value `"original color"` to all objects of type `Car`, and then overwrites that value with the string `"black"` only in the instance object `car1`. For more information, see [prototype](/en-US/docs/Learn/JavaScript/Objects/Object_prototypes).
```js
function Car() {}
const car1 = new Car();
const car2 = new Car();
console.log(car1.color); // undefined
Car.prototype.color = "original color";
console.log(car1.color); // 'original color'
car1.color = "black";
console.log(car1.color); // 'black'
console.log(Object.getPrototypeOf(car1).color); // 'original color'
console.log(Object.getPrototypeOf(car2).color); // 'original color'
console.log(car1.color); // 'black'
console.log(car2.color); // 'original color'
```
> **Note:** While the constructor function can be invoked like any regular function (i.e. without the `new` operator),
> in this case a new object is not created and the value of `this` is also different.
A function can know whether it is invoked with `new` by checking [`new.target`](/en-US/docs/Web/JavaScript/Reference/Operators/new.target). `new.target` is only `undefined` when the function is invoked without `new`. For example, you can have a function that behaves differently when it's called versus when it's constructed:
```js
function Car(color) {
if (!new.target) {
// Called as function.
return `${color} car`;
}
// Called with new.
this.color = color;
}
const a = Car("red"); // a is "red car"
const b = new Car("red"); // b is `Car { color: "red" }`
```
Prior to ES6, which introduced [classes](/en-US/docs/Web/JavaScript/Reference/Classes), most JavaScript built-ins are both callable and constructible, although many of them exhibit different behaviors. To name a few:
- [`Array()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Array), [`Error()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Error), and [`Function()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function) behave the same when called as a function or a constructor.
- [`Boolean()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/Boolean), [`Number()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/Number), and [`String()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/String) coerce their argument to the respective primitive type when called, and return wrapper objects when constructed.
- [`Date()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date) returns a string representing the current date when called, equivalent to `new Date().toString()`.
After ES6, the language is stricter about which are constructors and which are functions. For example:
- [`Symbol()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/Symbol) and [`BigInt()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/BigInt) can only be called without `new`. Attempting to construct them will throw a `TypeError`.
- [`Proxy`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy) and [`Map`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/Map) can only be constructed with `new`. Attempting to call them will throw a `TypeError`.
## Examples
### Object type and object instance
Suppose you want to create an object type for cars. You want this type of object to be
called `Car`, and you want it to have properties for make, model, and year.
To do this, you would write the following function:
```js
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
```
Now you can create an object called `myCar` as follows:
```js
const myCar = new Car("Eagle", "Talon TSi", 1993);
```
This statement creates `myCar` and assigns it the specified values for its
properties. Then the value of `myCar.make` is the string "Eagle",
`myCar.year` is the integer 1993, and so on.
You can create any number of `car` objects by calls to `new`. For
example:
```js
const kensCar = new Car("Nissan", "300ZX", 1992);
```
### Object property that is itself another object
Suppose you define an object called `Person` as follows:
```js
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
```
And then instantiate two new `Person` objects as follows:
```js
const rand = new Person("Rand McNally", 33, "M");
const ken = new Person("Ken Jones", 39, "M");
```
Then you can rewrite the definition of `Car` to include an
`owner` property that takes a `Person` object, as follows:
```js
function Car(make, model, year, owner) {
this.make = make;
this.model = model;
this.year = year;
this.owner = owner;
}
```
To instantiate the new objects, you then use the following:
```js
const car1 = new Car("Eagle", "Talon TSi", 1993, rand);
const car2 = new Car("Nissan", "300ZX", 1992, ken);
```
Instead of passing a literal string or integer value when creating the new objects, the
above statements pass the objects `rand` and `ken` as the
parameters for the owners. To find out the name of the owner of `car2`, you
can access the following property:
```js
car2.owner.name;
```
### Using `new` with classes
```js
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
const p = new Person("Caroline");
p.greet(); // Hello, my name is Caroline
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Function")}}
- {{jsxref("Reflect.construct()")}}
- {{jsxref("Object")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/operator_precedence/index.md | ---
title: Operator precedence
slug: Web/JavaScript/Reference/Operators/Operator_precedence
page-type: guide
---
{{jsSidebar("Operators")}}
**Operator precedence** determines how operators are parsed concerning each other. Operators with higher precedence become the operands of operators with lower precedence.
{{EmbedInteractiveExample("pages/js/expressions-operatorprecedence.html")}}
## Precedence and associativity
Consider an expression describable by the representation below, where both `OP1` and `OP2` are fill-in-the-blanks for OPerators.
```plain
a OP1 b OP2 c
```
The combination above has two possible interpretations:
```plain
(a OP1 b) OP2 c
a OP1 (b OP2 c)
```
Which one the language decides to adopt depends on the identity of `OP1` and `OP2`.
If `OP1` and `OP2` have different precedence levels (see the table below), the operator with the higher _precedence_ goes first and associativity does not matter. Observe how multiplication has higher precedence than addition and executed first, even though addition is written first in the code.
```js-nolint
console.log(3 + 10 * 2); // 23
console.log(3 + (10 * 2)); // 23, because parentheses here are superfluous
console.log((3 + 10) * 2); // 26, because the parentheses change the order
```
Within operators of the same precedence, the language groups them by _associativity_. _Left-associativity_ (left-to-right) means that it is interpreted as `(a OP1 b) OP2 c`, while _right-associativity_ (right-to-left) means it is interpreted as `a OP1 (b OP2 c)`. Assignment operators are right-associative, so you can write:
```js
a = b = 5; // same as writing a = (b = 5);
```
with the expected result that `a` and `b` get the value 5. This is because the assignment operator returns the value that is assigned. First, `b` is set to 5. Then the `a` is also set to 5 β the return value of `b = 5`, a.k.a. right operand of the assignment.
As another example, the unique exponentiation operator has right-associativity, whereas other arithmetic operators have left-associativity.
```js-nolint
const a = 4 ** 3 ** 2; // Same as 4 ** (3 ** 2); evaluates to 262144
const b = 4 / 3 / 2; // Same as (4 / 3) / 2; evaluates to 0.6666...
```
Operators are first grouped by precedence, and then, for adjacent operators that have the same precedence, by associativity. So, when mixing division and exponentiation, the exponentiation always comes before the division. For example, `2 ** 3 / 3 ** 2` results in 0.8888888888888888 because it is the same as `(2 ** 3) / (3 ** 2)`.
For prefix unary operators, suppose we have the following pattern:
```plain
OP1 a OP2 b
```
where `OP1` is a prefix unary operator and `OP2` is a binary operator. If `OP1` has higher precedence than `OP2`, then it would be grouped as `(OP1 a) OP2 b`; otherwise, it would be `OP1 (a OP2 b)`.
```js
const a = 1;
const b = 2;
typeof a + b; // Equivalent to (typeof a) + b; result is "number2"
```
If the unary operator is on the second operand:
```plain
a OP2 OP1 b
```
Then the binary operator `OP2` must have lower precedence than the unary operator `OP1` for it to be grouped as `a OP2 (OP1 b)`. For example, the following is invalid:
```js-nolint example-bad
function* foo() {
a + yield 1;
}
```
Because `+` has higher precedence than [`yield`](/en-US/docs/Web/JavaScript/Reference/Operators/yield), this would become `(a + yield) 1` β but because `yield` is a [reserved word](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#keywords) in generator functions, this would be a syntax error. Luckily, most unary operators have higher precedence than binary operators and do not suffer from this pitfall.
If we have two prefix unary operators:
```plain
OP1 OP2 a
```
Then the unary operator closer to the operand, `OP2`, must have higher precedence than `OP1` for it to be grouped as `OP1 (OP2 a)`. It's possible to get it the other way and end up with `(OP1 OP2) a`:
```js-nolint example-bad
async function* foo() {
await yield 1;
}
```
Because [`await`](/en-US/docs/Web/JavaScript/Reference/Operators/await) has higher precedence than [`yield`](/en-US/docs/Web/JavaScript/Reference/Operators/yield), this would become `(await yield) 1`, which is awaiting an identifier called `yield`, and a syntax error. Similarly, if you have `new !A;`, because `!` has lower precedence than `new`, this would become `(new !) A`, which is obviously invalid. (This code looks nonsensical to write anyway, since `!A` always produces a boolean, not a constructor function.)
For postfix unary operators (namely, `++` and `--`), the same rules apply. Luckily, both operators have higher precedence than any binary operator, so the grouping is always what you would expect. Moreover, because `++` evaluates to a _value_, not a _reference_, you can't chain multiple increments together either, as you may do in C.
```js-nolint example-bad
let a = 1;
a++++; // SyntaxError: Invalid left-hand side in postfix operation.
```
Operator precedence will be handled _recursively_. For example, consider this expression:
```js-nolint
1 + 2 ** 3 * 4 / 5 >> 6
```
First, we group operators with different precedence by decreasing levels of precedence.
1. The `**` operator has the highest precedence, so it's grouped first.
2. Looking around the `**` expression, it has `*` on the right and `+` on the left. `*` has higher precedence, so it's grouped first. `*` and `/` have the same precedence, so we group them together for now.
3. Looking around the `*`/`/` expression grouped in 2, because `+` has higher precedence than `>>`, the former is grouped.
```js-nolint
(1 + ( (2 ** 3) * 4 / 5) ) >> 6
// β β ββ 1. ββ β β
// β βββββββ 2. ββββββββ β
// βββββββββββ 3. βββββββββββ
```
Within the `*`/`/` group, because they are both left-associative, the left operand would be grouped.
```js-nolint
(1 + ( ( (2 ** 3) * 4 ) / 5) ) >> 6
// β β β ββ 1. ββ β β β
// β ββββββββββ 2. βββββββββ β
// βββββββββββββ 3. βββββββββββββ
// ββββββ 4. ββββββ
```
Note that operator precedence and associativity only affect the order of evaluation of _operators_ (the implicit grouping), but not the order of evaluation of _operands_. The operands are always evaluated from left-to-right. The higher-precedence expressions are always evaluated first, and their results are then composed according to the order of operator precedence.
```js-nolint
function echo(name, num) {
console.log(`Evaluating the ${name} side`);
return num;
}
// Exponentiation operator (**) is right-associative,
// but all call expressions (echo()), which have higher precedence,
// will be evaluated before ** does
console.log(echo("left", 4) ** echo("middle", 3) ** echo("right", 2));
// Evaluating the left side
// Evaluating the middle side
// Evaluating the right side
// 262144
// Exponentiation operator (**) has higher precedence than division (/),
// but evaluation always starts with the left operand
console.log(echo("left", 4) / echo("middle", 3) ** echo("right", 2));
// Evaluating the left side
// Evaluating the middle side
// Evaluating the right side
// 0.4444444444444444
```
If you are familiar with binary trees, think about it as a [post-order traversal](https://en.wikipedia.org/wiki/Tree_traversal#Post-order,_LRN).
```plain
/
ββββββββββ΄βββββββββ
echo("left", 4) **
ββββββββββ΄βββββββββ
echo("middle", 3) echo("right", 2)
```
After all operators have been properly grouped, the binary operators would form a binary tree. Evaluation starts from the outermost group β which is the operator with the lowest precedence (`/` in this case). The left operand of this operator is first evaluated, which may be composed of higher-precedence operators (such as a call expression `echo("left", 4)`). After the left operand has been evaluated, the right operand is evaluated in the same fashion. Therefore, all leaf nodes β the `echo()` calls β would be visited left-to-right, regardless of the precedence of operators joining them.
## Short-circuiting
In the previous section, we said "the higher-precedence expressions are always evaluated first" β this is generally true, but it has to be amended with the acknowledgement of _short-circuiting_, in which case an operand may not be evaluated at all.
Short-circuiting is jargon for conditional evaluation. For example, in the expression `a && (b + c)`, if `a` is {{Glossary("falsy")}}, then the sub-expression `(b + c)` will not even get evaluated, even if it is grouped and therefore has higher precedence than `&&`. We could say that the logical AND operator (`&&`) is "short-circuited". Along with logical AND, other short-circuited operators include logical OR (`||`), nullish coalescing (`??`), and optional chaining (`?.`).
```js-nolint
a || (b * c); // evaluate `a` first, then produce `a` if `a` is "truthy"
a && (b < c); // evaluate `a` first, then produce `a` if `a` is "falsy"
a ?? (b || c); // evaluate `a` first, then produce `a` if `a` is not `null` and not `undefined`
a?.b.c; // evaluate `a` first, then produce `undefined` if `a` is `null` or `undefined`
```
When evaluating a short-circuited operator, the left operand is always evaluated. The right operand will only be evaluated if the left operand cannot determine the result of the operation.
> **Note:** The behavior of short-circuiting is baked in these operators. Other operators would _always_ evaluate both operands, regardless if that's actually useful β for example, `NaN * foo()` will always call `foo`, even when the result would never be something other than `NaN`.
The previous model of a post-order traversal still stands. However, after the left subtree of a short-circuiting operator has been visited, the language will decide if the right operand needs to be evaluated. If not (for example, because the left operand of `||` is already truthy), the result is directly returned without visiting the right subtree.
Consider this case:
```js-nolint
function A() { console.log('called A'); return false; }
function B() { console.log('called B'); return false; }
function C() { console.log('called C'); return true; }
console.log(C() || B() && A());
// Logs:
// called C
// true
```
Only `C()` is evaluated, despite `&&` having higher precedence. This does not mean that `||` has higher precedence in this case β it's exactly _because_ `(B() && A())` has higher precedence that causes it to be neglected as a whole. If it's re-arranged as:
```js-nolint
console.log(A() && C() || B());
// Logs:
// called A
// called B
// false
```
Then the short-circuiting effect of `&&` would only prevent `C()` from being evaluated, but because `A() && C()` as a whole is `false`, `B()` would still be evaluated.
However, note that short-circuiting does not change the final evaluation outcome. It only affects the evaluation of _operands_, not how _operators_ are grouped β if evaluation of operands doesn't have side effects (for example, logging to the console, assigning to variables, throwing an error), short-circuiting would not be observable at all.
The assignment counterparts of these operators ([`&&=`](/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND_assignment), [`||=`](/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR_assignment), [`??=`](/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_assignment)) are short-circuited as well. They are short-circuited in a way that the assignment does not happen at all.
## Table
The following table lists operators in order from highest precedence (18) to lowest precedence (1).
Several general notes about the table:
1. Not all syntax included here are "operators" in the strict sense. For example, spread `...` and arrow `=>` are typically not regarded as operators. However, we still included them to show how tightly they bind compared to other operators/expressions.
2. Some operators have certain operands that require expressions narrower than those produced by higher-precedence operators. For example, the right-hand side of member access `.` (precedence 17) must be an identifier instead of a grouped expression. The left-hand side of arrow `=>` (precedence 2) must be an arguments list or a single identifier instead of some random expression.
3. Some operators have certain operands that accept expressions wider than those produced by higher-precedence operators. For example, the bracket-enclosed expression of bracket notation `[ β¦ ]` (precedence 17) can be any expression, even comma (precedence 1) joined ones. These operators act as if that operand is "automatically grouped". In this case we will omit the associativity.
<table class="fullwidth-table">
<tbody>
<tr>
<th>Precedence</th>
<th>Associativity</th>
<th>Individual operators</th>
<th>Notes</th>
</tr>
<tr>
<td>18: grouping</td>
<td>n/a</td>
<td>{{jsxref("Operators/Grouping", "Grouping", "", 1)}}<br><code>(x)</code></td>
<td>[1]</td>
</tr>
<tr>
<td rowspan="6">17: access and call</td>
<td rowspan="2">
left-to-right
</td>
<td>{{jsxref("Operators/Property_accessors", "Member access", "#dot_notation", 1)}}<br><code>x.y</code></td>
<td rowspan="2">[2]</td>
</tr>
<tr>
<td>{{jsxref("Operators/Optional_chaining", "Optional chaining", "", 1)}}<br><code>x?.y</code></td>
</tr>
<tr>
<td rowspan="4">n/a</td>
<td>
{{jsxref("Operators/Property_accessors", "Computed member access", "#bracket_notation", 1)}}<br><code>x[y]</code>
</td>
<td>[3]</td>
</tr>
<tr>
<td>{{jsxref("Operators/new", "new")}} with argument list<br><code>new x(y)</code></td>
<td rowspan="3">[4]</td>
</tr>
<tr>
<td>
<a href="/en-US/docs/Web/JavaScript/Guide/Functions">Function call</a><br><code>x(y)</code>
</td>
</tr>
<tr>
<td>{{jsxref("Operators/import", "import(x)")}}</td>
</tr>
<tr>
<td>16: new</td>
<td>n/a</td>
<td>{{jsxref("Operators/new", "new")}} without argument list<br><code>new x</code></td>
</tr>
<tr>
<td rowspan="2">15: postfix operators</td>
<td rowspan="2">n/a</td>
<td>
{{jsxref("Operators/Increment", "Postfix increment", "", 1)}}<br><code>x++</code>
</td>
<td rowspan="2">[5]</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Decrement", "Postfix decrement", "", 1)}}<br><code>x--</code>
</td>
</tr>
<tr>
<td rowspan="10">14: prefix operators</td>
<td rowspan="10">n/a</td>
<td>
{{jsxref("Operators/Increment", "Prefix increment", "", 1)}}<br><code>++x</code>
</td>
<td rowspan="2">[6]</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Decrement", "Prefix decrement", "", 1)}}<br><code>--x</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Logical_NOT", "Logical NOT", "", 1)}}<br><code>!x</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Bitwise_NOT", "Bitwise NOT", "", 1)}}<br><code>~x</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Unary_plus", "Unary plus", "", 1)}}<br><code>+x</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Unary_negation", "Unary negation", "", 1)}}<br><code>-x</code>
</td>
</tr>
<tr>
<td>{{jsxref("Operators/typeof", "typeof x")}}</td>
</tr>
<tr>
<td>{{jsxref("Operators/void", "void x")}}</td>
</tr>
<tr>
<td>{{jsxref("Operators/delete", "delete x")}}</td>
<td>[7]</td>
</tr>
<tr>
<td>{{jsxref("Operators/await", "await x")}}</td>
</tr>
<tr>
<td>13: exponentiation</td>
<td>right-to-left</td>
<td>
{{jsxref("Operators/Exponentiation", "Exponentiation", "", 1)}}<br><code>x ** y</code>
</td>
<td>[8]</td>
</tr>
<tr>
<td rowspan="3">12: multiplicative operators</td>
<td rowspan="3">left-to-right</td>
<td>
{{jsxref("Operators/Multiplication", "Multiplication", "", 1)}}<br><code>x * y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Division", "Division", "", 1)}}<br><code>x / y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Remainder", "Remainder", "", 1)}}<br><code>x % y</code>
</td>
</tr>
<tr>
<td rowspan="2">11: additive operators</td>
<td rowspan="2">left-to-right</td>
<td>
{{jsxref("Operators/Addition", "Addition", "", 1)}}<br><code>x + y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Subtraction", "Subtraction", "", 1)}}<br><code>x - y</code>
</td>
</tr>
<tr>
<td rowspan="3">10: bitwise shift</td>
<td rowspan="3">left-to-right</td>
<td>
{{jsxref("Operators/Left_shift", "Left shift", "", 1)}}<br><code>x << y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Right_shift", "Right shift", "", 1)}}<br><code>x >> y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Unsigned_right_shift", "Unsigned right shift", "", 1)}}<br><code>x >>> y</code>
</td>
</tr>
<tr>
<td rowspan="6">9: relational operators</td>
<td rowspan="6">left-to-right</td>
<td>
{{jsxref("Operators/Less_than", "Less than", "", 1)}}<br><code>x < y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Less_than_or_equal", "Less than or equal", "", 1)}}<br><code>x <= y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Greater_than", "Greater than", "", 1)}}<br><code>x > y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Greater_than_or_equal", "Greater than or equal", "", 1)}}<br><code>x >= y</code>
</td>
</tr>
<tr>
<td>{{jsxref("Operators/in", "x in y")}}</td>
</tr>
<tr>
<td>{{jsxref("Operators/instanceof", "x instanceof y")}}</td>
</tr>
<tr>
<td rowspan="4">8: equality operators</td>
<td rowspan="4">left-to-right</td>
<td>
{{jsxref("Operators/Equality", "Equality", "", 1)}}<br><code>x == y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Inequality", "Inequality", "", 1)}}<br><code>x != y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Strict_equality", "Strict equality", "", 1)}}<br><code>x === y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Strict_inequality", "Strict inequality", "", 1)}}<br><code>x !== y</code>
</td>
</tr>
<tr>
<td>7: bitwise AND</td>
<td>left-to-right</td>
<td>
{{jsxref("Operators/Bitwise_AND", "Bitwise AND", "", 1)}}<br><code>x & y</code>
</td>
</tr>
<tr>
<td>6: bitwise XOR</td>
<td>left-to-right</td>
<td>
{{jsxref("Operators/Bitwise_XOR", "Bitwise XOR", "", 1)}}<br><code>x ^ y</code>
</td>
</tr>
<tr>
<td>5: bitwise OR</td>
<td>left-to-right</td>
<td>
{{jsxref("Operators/Bitwise_OR", "Bitwise OR", "", 1)}}<br><code>x | y</code>
</td>
</tr>
<tr>
<td>4: logical AND</td>
<td>left-to-right</td>
<td>
{{jsxref("Operators/Logical_AND", "Logical AND", "", 1)}}<br><code>x && y</code>
</td>
</tr>
<tr>
<td rowspan="2">3: logical OR, nullish coalescing</td>
<td rowspan="2">left-to-right</td>
<td>
{{jsxref("Operators/Logical_OR", "Logical OR", "", 1)}}<br><code>x || y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Nullish_coalescing", "Nullish coalescing operator", "", 1)}}<br><code>x ?? y</code>
</td>
<td>[9]</td>
</tr>
<tr>
<td rowspan="21">2: assignment and miscellaneous</td>
<td rowspan="16">right-to-left</td>
<td>
{{jsxref("Operators/Assignment", "Assignment", "", 1)}}<br><code>x = y</code>
</td>
<td rowspan="16">[10]</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Addition_assignment", "Addition assignment", "", 1)}}<br><code>x += y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Subtraction_assignment", "Subtraction assignment", "", 1)}}<br><code>x -= y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Exponentiation_assignment", "Exponentiation assignment", "", 1)}}<br><code>x **= y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Multiplication_assignment", "Multiplication assignment", "", 1)}}<br><code>x *= y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Division_assignment", "Division assignment", "", 1)}}<br><code>x /= y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Remainder_assignment", "Remainder assignment", "", 1)}}<br><code>x %= y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Left_shift_assignment", "Left shift assignment", "", 1)}}<br><code>x <<= y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Right_shift_assignment", "Right shift assignment", "", 1)}}<br><code>x >>= y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Unsigned_right_shift_assignment", "Unsigned right shift assignment", "", 1)}}<br><code>x >>>= y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Bitwise_AND_assignment", "Bitwise AND assignment", "", 1)}}<br><code>x &= y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Bitwise_XOR_assignment", "Bitwise XOR assignment", "", 1)}}<br><code>x ^= y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Bitwise_OR_assignment", "Bitwise OR assignment", "", 1)}}<br><code>x |= y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Logical_AND_assignment", "Logical AND assignment", "", 1)}}<br><code>x &&= y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Logical_OR_assignment", "Logical OR assignment", "", 1)}}<br><code>x ||= y</code>
</td>
</tr>
<tr>
<td>
{{jsxref("Operators/Nullish_coalescing_assignment", "Nullish coalescing assignment", "", 1)}}<br><code>x ??= y</code>
</td>
</tr>
<tr>
<td>right-to-left</td>
<td>
<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator">Conditional (ternary) operator</a><br><code>x ? y : z</code>
</td>
<td>[11]</td>
</tr>
<tr>
<td>right-to-left</td>
<td>
<a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow</a><br><code>x => y</code>
</td>
<td>[12]</td>
</tr>
<tr>
<td rowspan="3">n/a</td>
<td>{{jsxref("Operators/yield", "yield x")}}</td>
</tr>
<tr>
<td>{{jsxref("Operators/yield*", "yield* x")}}</td>
</tr>
<tr>
<td>
<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">Spread</a><br><code>...x</code>
</td>
<td>[13]</td>
</tr>
<tr>
<td>1: comma</td>
<td>left-to-right</td>
<td>
{{jsxref("Operators/Comma_Operator", "Comma operator", "", 1)}}<br><code>x, y</code>
</td>
</tr>
</tbody>
</table>
Notes:
1. The operand can be any expression.
2. The "right-hand side" must be an identifier.
3. The "right-hand side" can be any expression.
4. The "right-hand side" is a comma-separated list of any expression with precedence > 1 (i.e. not comma expressions).
5. The operand must be a valid assignment target (identifier or property access). Its precedence means `new Foo++` is `(new Foo)++` (a syntax error) and not `new (Foo++)` (a TypeError: (Foo++) is not a constructor).
6. The operand must be a valid assignment target (identifier or property access).
7. The operand cannot be an identifier or a [private property](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties) access.
8. The left-hand side cannot have precedence 14.
9. The operands cannot be a logical OR `||` or logical AND `&&` operator without grouping.
10. The "left-hand side" must be a valid assignment target (identifier or property access).
11. The associativity means the two expressions after `?` are implicitly grouped.
12. The "left-hand side" is a single identifier or a parenthesized parameter list.
13. Only valid inside object literals, array literals, or argument lists.
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/nullish_coalescing_assignment/index.md | ---
title: Nullish coalescing assignment (??=)
slug: Web/JavaScript/Reference/Operators/Nullish_coalescing_assignment
page-type: javascript-operator
browser-compat: javascript.operators.nullish_coalescing_assignment
---
{{jsSidebar("Operators")}}
The **nullish coalescing assignment (`??=`)** operator, also known as the **logical nullish assignment** operator, only evaluates the right operand and assigns to the left if the left operand is {{Glossary("nullish")}} (`null` or `undefined`).
{{EmbedInteractiveExample("pages/js/expressions-nullish-coalescing-assignment.html")}}
## Syntax
```js-nolint
x ??= y
```
## Description
Nullish coalescing assignment [_short-circuits_](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence#short-circuiting), meaning that `x ??= y` is equivalent to `x ?? (x = y)`, except that the expression `x` is only evaluated once.
No assignment is performed if the left-hand side is not nullish, due to short-circuiting of the [nullish coalescing](/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing) operator. For example, the following does not throw an error, despite `x` being `const`:
```js
const x = 1;
x ??= 2;
```
Neither would the following trigger the setter:
```js
const x = {
get value() {
return 1;
},
set value(v) {
console.log("Setter called");
},
};
x.value ??= 2;
```
In fact, if `x` is not nullish, `y` is not evaluated at all.
```js
const x = 1;
x ??= console.log("y evaluated");
// Logs nothing
```
## Examples
### Using nullish coalescing assignment
You can use the nullish coalescing assignment operator to apply default values to object properties. Compared to using destructuring and [default values](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value), `??=` also applies the default value if the property has value `null`.
```js
function config(options) {
options.duration ??= 100;
options.speed ??= 25;
return options;
}
config({ duration: 125 }); // { duration: 125, speed: 25 }
config({}); // { duration: 100, speed: 25 }
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Nullish coalescing operator (`??`)](/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing)
- {{Glossary("Nullish")}}
- {{Glossary("Truthy")}}
- {{Glossary("Falsy")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/class/index.md | ---
title: class expression
slug: Web/JavaScript/Reference/Operators/class
page-type: javascript-operator
browser-compat: javascript.operators.class
---
{{jsSidebar("Operators")}}
The **`class`** keyword can be used to define a class inside an expression.
You can also define classes using the [`class` declaration](/en-US/docs/Web/JavaScript/Reference/Statements/class).
{{EmbedInteractiveExample("pages/js/expressions-classexpression.html")}}
## Syntax
```js-nolint
class {
// class body
}
class name {
// class body
}
```
> **Note:** An [expression statement](/en-US/docs/Web/JavaScript/Reference/Statements/Expression_statement) cannot begin with the keyword `class` to avoid ambiguity with a [`class` declaration](/en-US/docs/Web/JavaScript/Reference/Statements/class). The `class` keyword only begins an expression when it appears in a context that cannot accept statements.
## Description
A `class` expression is very similar to, and has almost the same syntax as, a [`class` declaration](/en-US/docs/Web/JavaScript/Reference/Statements/class). As with `class` declarations, the body of a `class` expression is executed in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode). The main difference between a `class` expression and a `class` declaration is the _class name_, which can be omitted in `class` expressions to create _anonymous_ classes. Class expressions allow you to redefine classes, while redeclaring a class using `class` declarations throws a {{jsxref("SyntaxError")}}. See also the chapter about [classes](/en-US/docs/Web/JavaScript/Reference/Classes) for more information.
## Examples
### A simple class expression
This is just a simple anonymous class expression which you can refer to using the variable `Foo`.
```js
const Foo = class {
constructor() {}
bar() {
return "Hello World!";
}
};
const instance = new Foo();
instance.bar(); // "Hello World!"
Foo.name; // "Foo"
```
### Named class expressions
If you want to refer to the current class inside the class body, you can create a _named class expression_. The name is only visible within the scope of the class expression itself.
```js
const Foo = class NamedFoo {
constructor() {}
whoIsThere() {
return NamedFoo.name;
}
};
const bar = new Foo();
bar.whoIsThere(); // "NamedFoo"
NamedFoo.name; // ReferenceError: NamedFoo is not defined
Foo.name; // "NamedFoo"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Statements/class", "class")}}
- {{jsxref("Classes", "Classes", "", "true")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/property_accessors/index.md | ---
title: Property accessors
slug: Web/JavaScript/Reference/Operators/Property_accessors
page-type: javascript-operator
browser-compat: javascript.operators.property_accessors
---
{{jsSidebar("Operators")}}
**Property accessors** provide access to an object's properties by using the dot notation or the bracket notation.
{{EmbedInteractiveExample("pages/js/expressions-propertyaccessors.html", "taller")}}
## Syntax
```js-nolint
object.propertyName
object[expression]
```
## Description
One can think of an object as an _associative array_ (a.k.a. _map_, _dictionary_, _hash_, _lookup table_). The _keys_ in this array are the names of the object's [properties](/en-US/docs/Glossary/Property/JavaScript).
There are two ways to access properties: _dot notation_ and _bracket notation_.
### Dot notation
In the `object.propertyName` syntax, the `propertyName` must be a valid JavaScript [identifier](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers) which can also be a [reserved word](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#keywords). For example, `object.$1` is valid, while `object.1` is not.
```js
const variable = object.propertyName;
object.propertyName = value;
```
```js
const object = {};
object.$1 = "foo";
console.log(object.$1); // 'foo'
```
```js-nolint example-bad
const object = {};
object.1 = 'bar'; // SyntaxError
console.log(object.1); // SyntaxError
```
Here, the method named `createElement` is retrieved from `document` and is called.
```js
document.createElement("pre");
```
If you use a method for a numeric literal, and the numeric literal has no exponent and no decimal point, you should leave [white-space(s)](/en-US/docs/Glossary/Whitespace) before the dot preceding the method call, so that the dot is not interpreted as a decimal point.
```js-nolint
77 .toExponential();
// or
77
.toExponential();
// or
(77).toExponential();
// or
77..toExponential();
// or
77.0.toExponential();
// because 77. === 77.0, no ambiguity
```
### Bracket notation
In the `object[expression]` syntax, the `expression` should evaluate to a string or [Symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) that represents the property's name. So, it can be any string literal, for example, including `'1foo'`, `'!bar!'`, or even `' '` (a space).
```js
const variable = object[propertyName];
object[propertyName] = value;
```
This does the exact same thing as the previous example.
```js
document["createElement"]("pre");
```
A space before bracket notation is allowed.
```js-nolint
document ["createElement"]("pre");
```
Passing expressions that evaluate to property name will do the same thing as directly passing the property name.
```js
const key = "name";
const getKey = () => "name";
const Obj = { name: "Michel" };
Obj["name"]; // returns "Michel"
Obj[key]; // evaluates to Obj["name"], and returns "Michel"
Obj[getKey()]; // evaluates to Obj["name"], and returns "Michel"
```
However, beware of using square brackets to access properties whose names are given by external input. This may make your code susceptible to [object injection attacks](https://github.com/nodesecurity/eslint-plugin-security/blob/main/docs/the-dangers-of-square-bracket-notation.md).
### Property names
Each property name is a string or a [Symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol). Any other value, including a number, is coerced to a string. This outputs `'value'`, since `1` is coerced into `'1'`.
```js
const object = {};
object["1"] = "value";
console.log(object[1]);
```
This also outputs `'value'`, since both `foo` and `bar` are converted to the same string (`"[object Object]"`).
```js
const foo = { uniqueProp: 1 };
const bar = { uniqueProp: 2 };
const object = {};
object[foo] = "value";
console.log(object[bar]);
```
### Method binding
It's typical when speaking of an object's properties to make a distinction between properties and methods. However, the property/method distinction is little more than a convention. A method is a property that can be called (for example, if it has a reference to a {{jsxref("Function")}} instance as its value).
A method is not bound to the object that it is a property of. Specifically, `this` is not fixed in a method and does not necessarily refer to the object containing the method. Instead, `this` is "passed" by the function call. See [the reference for `this`](/en-US/docs/Web/JavaScript/Reference/Operators/this).
## Examples
### Bracket notation vs. eval()
JavaScript novices often make the mistake of using {{jsxref("Global_Objects/eval", "eval()")}} where the bracket notation can be used instead.
For example, the following syntax is often seen in many scripts.
```js
const x = eval(`document.forms.form_name.elements.${strFormControl}.value`);
```
`eval()` is slow and should be avoided whenever possible. Also, `strFormControl` would have to hold an identifier, which is not required for names and `id`s of form controls. It is better to use bracket notation instead:
```js
const x = document.forms.form_name.elements[strFormControl].value;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Object")}}
- {{jsxref("Object.defineProperty()")}}
- [Optional chaining (`?.`)](/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/multiplication/index.md | ---
title: Multiplication (*)
slug: Web/JavaScript/Reference/Operators/Multiplication
page-type: javascript-operator
browser-compat: javascript.operators.multiplication
---
{{jsSidebar("Operators")}}
The **multiplication (`*`)** operator produces the product of the operands.
{{EmbedInteractiveExample("pages/js/expressions-multiplication.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 multiplication if both operands become BigInts; otherwise, it performs number multiplication. A {{jsxref("TypeError")}} is thrown if one operand becomes a BigInt but the other becomes a number.
## Examples
### Multiplication using numbers
```js
2 * 2; // 4
-2 * 2; // -4
```
### Multiplication with Infinity
```js
Infinity * 0; // NaN
Infinity * Infinity; // Infinity
```
### Multiplication with non-numbers
```js
"foo" * 2; // NaN
"2" * 2; // 4
```
### Multiplication using BigInts
```js
2n * 2n; // 4n
-2n * 2n; // -4n
2n * 2; // TypeError: Cannot mix BigInt and other types, use explicit conversions
// To multiply a BigInt with a non-BigInt, convert either operand
2n * BigInt(2); // 4n
Number(2n) * 2; // 4
```
## 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)
- [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)
- [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)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/yield_star_/index.md | ---
title: yield*
slug: Web/JavaScript/Reference/Operators/yield*
page-type: javascript-operator
browser-compat: javascript.operators.yield_star
---
{{jsSidebar("Operators")}}
The **`yield*`** operator is used to delegate to another [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) object, such as a {{jsxref("Generator")}}.
{{EmbedInteractiveExample("pages/js/expressions-yieldasterisk.html")}}
## Syntax
```js-nolint
yield* expression
```
### Parameters
- `expression` {{optional_inline}}
- : An iterable object.
### Return value
Returns the value returned by that iterator when it's closed (when `done` is `true`).
## Description
The `yield*` expression iterates over the operand and yields each value returned by it. It delegates iteration of the current generator to an underlying iterator β which we will refer to as "generator" and "iterator", respectively. `yield*` first gets the iterator from the operand by calling the latter's [`@@iterator`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator) method. Then, each time the `next()` method of the generator is called, `yield*` calls the iterator's `next()` method, passing the argument received by the generator's `next()` method (always `undefined` for the first call), and yielding the same result object as what's returned from the iterator's `next()` method. If the iterator result has `done: true`, then the `yield*` expression stops executing and returns the `value` of that result.
The `yield*` operator forwards the current generator's {{jsxref("Generator/throw", "throw()")}} and {{jsxref("Generator/return", "return()")}} methods to the underlying iterator as well. If the current generator is prematurely closed through one of these methods, the underlying iterator will be notified. If the generator's `throw()`/`return()` method is called, the `throw()`/`return()` method of the underlying iterator is called with the same argument. The return value of `throw()`/`return()` is handled like the `next()` method's result, and if the method throws, the exception is propagated from the `yield*` expression.
If the underlying iterator doesn't have a `throw()` method, this causes `yield*` to throw a {{jsxref("TypeError")}} β but before throwing the error, the underlying iterator's `return()` method is called if one exists. If the underlying iterator doesn't have a `return()` method, the `yield*` expression turns into a {{jsxref("Statements/return", "return")}} statement, just like calling `return()` on a suspended {{jsxref("Operators/yield", "yield")}} expression.
## Examples
### Delegating to another generator
In following code, values yielded by `g1()` are returned from
`next()` calls just like those which are yielded by `g2()`.
```js
function* g1() {
yield 2;
yield 3;
yield 4;
}
function* g2() {
yield 1;
yield* g1();
yield 5;
}
const gen = g2();
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: 4, done: false}
console.log(gen.next()); // {value: 5, done: false}
console.log(gen.next()); // {value: undefined, done: true}
```
### Other Iterable objects
Besides generator objects, `yield*` can also `yield` other kinds
of iterables (e.g., arrays, strings, or {{jsxref("Functions/arguments", "arguments")}}
objects).
```js
function* g3(...args) {
yield* [1, 2];
yield* "34";
yield* args;
}
const gen = g3(5, 6);
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: "4", done: false}
console.log(gen.next()); // {value: 5, done: false}
console.log(gen.next()); // {value: 6, done: false}
console.log(gen.next()); // {value: undefined, done: true}
```
### The value of yield\* expression itself
`yield*` is an expression, not a statement, so it evaluates to a value.
```js
function* g4() {
yield* [1, 2, 3];
return "foo";
}
function* g5() {
const g4ReturnValue = yield* g4();
console.log(g4ReturnValue); // 'foo'
return g4ReturnValue;
}
const gen = g5();
console.log(gen.next()); // {value: 1, done: false}
console.log(gen.next()); // {value: 2, done: false}
console.log(gen.next()); // {value: 3, done: false} done is false because g5 generator isn't finished, only g4
console.log(gen.next()); // {value: 'foo', done: true}
```
### Method forwarding
The `next()`, `throw()`, and `return()` methods of the current generator are all forwarded to the underlying iterator.
```js
const iterable = {
[Symbol.iterator]() {
let count = 0;
return {
next(v) {
console.log("next called with", v);
count++;
return { value: count, done: false };
},
return(v) {
console.log("return called with", v);
return { value: "iterable return value", done: true };
},
throw(v) {
console.log("throw called with", v);
return { value: "iterable thrown value", done: true };
},
};
},
};
function* gf() {
yield* iterable;
return "gf return value";
}
const gen = gf();
console.log(gen.next(10));
// next called with undefined; the argument of the first next() call is always ignored
// { value: 1, done: false }
console.log(gen.next(20));
// next called with 20
// { value: 2, done: false }
console.log(gen.return(30));
// return called with 30
// { value: 'iterable return value', done: true }
console.log(gen.next(40));
// { value: undefined, done: true }; gen is already closed
const gen2 = gf();
console.log(gen2.next(10));
// next called with undefined
// { value: 1, done: false }
console.log(gen2.throw(50));
// throw called with 50
// { value: 'gf return value', done: true }
console.log(gen.next(60));
// { value: undefined, done: true }; gen is already closed
```
If the `return()`/`throw()` method of the underlying iterator returns `done: false`, the current generator continues executing and `yield*` continues to delegate to the underlying iterator.
```js
const iterable = {
[Symbol.iterator]() {
let count = 0;
return {
next(v) {
console.log("next called with", v);
count++;
return { value: count, done: false };
},
return(v) {
console.log("return called with", v);
return { value: "iterable return value", done: false };
},
};
},
};
function* gf() {
yield* iterable;
return "gf return value";
}
const gen = gf();
console.log(gen.next(10));
// next called with undefined
// { value: 1, done: false }
console.log(gen.return(20));
// return called with 20
// { value: 'iterable return value', done: false }
console.log(gen.next(30));
// { value: 2, done: false }; gen is not closed
```
If the underlying iterator doesn't have a `throw()` method and the generator's `throw()` is called, `yield*` throws an error.
```js
const iterable = {
[Symbol.iterator]() {
let count = 0;
return {
next(v) {
count++;
return { value: count, done: false };
},
};
},
};
function* gf() {
yield* iterable;
return "gf return value";
}
const gen = gf();
gen.next(); // First next() starts the yield* expression
gen.throw(20); // TypeError: The iterator does not provide a 'throw' method.
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
- {{jsxref("Statements/function*", "function*")}}
- [`function*` expression](/en-US/docs/Web/JavaScript/Reference/Operators/function*)
- {{jsxref("Operators/yield", "yield")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/comma_operator/index.md | ---
title: Comma operator (,)
slug: Web/JavaScript/Reference/Operators/Comma_operator
page-type: javascript-operator
browser-compat: javascript.operators.comma
---
{{jsSidebar("Operators")}}
The **comma (`,`)** operator evaluates each of its operands (from left to right) and returns the value of the last operand. This is commonly used to provide multiple updaters to a [`for`](/en-US/docs/Web/JavaScript/Reference/Statements/for) loop's afterthought.
{{EmbedInteractiveExample("pages/js/expressions-commaoperators.html")}}
## Syntax
```js-nolint
expr1, expr2, expr3/* , β¦ */
```
### Parameters
- `expr1`, `expr2`, `expr3`, β¦
- : One or more expressions, the last of which is returned as the value of the compound expression.
## Description
You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple updaters in a `for` loop.
Because all expressions except the last are evaluated and then discarded, these expressions must have side effects to be useful. Common expressions that have side effects are assignments, function calls, and [`++`](/en-US/docs/Web/JavaScript/Reference/Operators/Increment) and [`--`](/en-US/docs/Web/JavaScript/Reference/Operators/Decrement) operators. 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).
The comma operator has the lowest [precedence](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence) of all operators. If you want to incorporate a comma-joined expression into a bigger expression, you must parenthesize it.
The comma operator is completely different from commas used as syntactic separators in other locations, which include:
- Elements in array initializers (`[1, 2, 3]`)
- Properties in [object initializers](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) (`{ a: 1, b: 2 }`)
- Parameters in [function declarations](/en-US/docs/Web/JavaScript/Reference/Statements/function)/expressions (`function f(a, b) { β¦ }`)
- Arguments in function calls (`f(1, 2)`)
- {{Glossary("Binding")}} lists in [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let), [`const`](/en-US/docs/Web/JavaScript/Reference/Statements/const), or [`var`](/en-US/docs/Web/JavaScript/Reference/Statements/var) declarations (`const a = 1, b = 2;`)
- Import lists in [`import`](/en-US/docs/Web/JavaScript/Reference/Statements/import) declarations (`import { a, b } from "c";`)
- Export lists in [`export`](/en-US/docs/Web/JavaScript/Reference/Statements/export) declarations (`export { a, b };`)
In fact, although some of these places accept almost all expressions, they don't accept comma-joined expressions because that would be ambiguous with the syntactic comma separators. In this case, you must parenthesize the comma-joined expression. For example, the following is a `const` declaration that declares two variables, where the comma is not the comma operator:
```js-nolint
const a = 1, b = 2;
```
It is different from the following, where `b = 2` is an [assignment expression](/en-US/docs/Web/JavaScript/Reference/Operators/Assignment), not a declaration. The value of `a` is `2`, the return value of the assignment, while the value of `1` is discarded:
```js-nolint
const a = (1, b = 2);
```
Comma operators cannot appear as [trailing commas](/en-US/docs/Web/JavaScript/Reference/Trailing_commas).
## Examples
### Using the comma operator in a for loop
If `a` is a 2-dimensional array with 10 elements on each side, the following code uses the comma operator to increment `i` and decrement `j` at once, thus printing the values of the diagonal elements in the array:
```js
const a = Array.from({ length: 10 }, () =>
Array.from({ length: 10 }, Math.random),
); // A 10Γ10 array of random numbers
for (let i = 0, j = 9; i <= 9; i++, j--) {
console.log(`a[${i}][${j}] = ${a[i][j]}`);
}
```
### Using the comma operator to join assignments
Because commas have the lowest [precedence](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence) β even lower than assignment β commas can be used to join multiple assignment expressions. In the following example, `a` is set to the value of `b = 3` (which is 3). Then, the `c = 4` expression evaluates and its result becomes the return value of the entire comma expression.
```js-nolint
let a, b, c;
a = b = 3, c = 4; // Returns 4
console.log(a); // 3 (left-most)
let x, y, z;
x = (y = 5, z = 6); // Returns 6
console.log(x); // 6 (right-most)
```
### Processing and then returning
Another example that one could make with the comma operator is processing before returning. As stated, only the last element will be returned but all others are going to be evaluated as well. So, one could do:
```js-nolint
function myFunc() {
let x = 0;
return (x += 1, x); // the same as return ++x;
}
```
This is especially useful for one-line [arrow functions](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). The following example uses a single [`map()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) to get both the sum of an array and the squares of its elements, which would otherwise require two iterations, one with [`reduce()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) and one with `map()`:
```js
let sum = 0;
const squares = [1, 2, 3, 4, 5].map((x) => ((sum += x), x * x));
console.log(squares); // [1, 4, 9, 16, 25]
console.log(sum); // 15
```
### Discarding reference binding
The comma operator always returns the last expression as a _value_ instead of a _reference_. This causes some contextual information such as the [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this) binding to be lost. For example, a property access returns a reference to the function, which also remembers the object that it's accessed on, so that calling the property works properly. If the method is returned from a comma expression, then the function is called as if it's a new function value, and `this` is `undefined`.
```js-nolint
const obj = {
value: "obj",
method() {
console.log(this.value);
},
};
obj.method(); // "obj"
(obj.method)(); // "obj" (the grouping operator still returns the reference)
(0, obj.method)(); // undefined (the comma operator returns a new value)
```
You can enter [indirect eval](/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#direct_and_indirect_eval) with this technique, because direct eval requires the function call to happen on the reference to the `eval()` function.
```js-nolint
globalThis.isDirectEval = false;
{
const isDirectEval = true;
console.log(eval("isDirectEval")); // true
console.log((eval)("isDirectEval")); // true (the grouping operator still returns a reference to `eval`)
console.log((0, eval)("isDirectEval")); // false (the comma operator returns a new value)
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`for`](/en-US/docs/Web/JavaScript/Reference/Statements/for)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/import/index.md | ---
title: import()
slug: Web/JavaScript/Reference/Operators/import
page-type: javascript-operator
browser-compat: javascript.operators.import
---
{{jsSidebar("Operators")}}
The **`import()`** syntax, commonly called _dynamic import_, is a function-like expression that allows loading an ECMAScript module asynchronously and dynamically into a potentially non-module environment.
Unlike the [declaration-style counterpart](/en-US/docs/Web/JavaScript/Reference/Statements/import), dynamic imports are only evaluated when needed, and permit greater syntactic flexibility.
## Syntax
```js-nolint
import(moduleName)
```
The `import()` call is a syntax that closely resembles a function call, but `import` itself is a keyword, not a function. You cannot alias it like `const myImport = import`, which will throw a {{jsxref("SyntaxError")}}.
### Parameters
- `moduleName`
- : The module to import from. The evaluation of the specifier is host-specified, but always follows the same algorithm as static [import declarations](/en-US/docs/Web/JavaScript/Reference/Statements/import).
### Return value
Returns a promise which fulfills to a [module namespace object](#module_namespace_object): an object containing all exports from `moduleName`.
The evaluation of `import()` never synchronously throws an error. `moduleName` is [coerced to a string](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), and if coercion throws, the promise is rejected with the thrown error.
## Description
The import declaration syntax (`import something from "somewhere"`) is static and will always result in the imported module being evaluated at load time. Dynamic imports allow one to circumvent the syntactic rigidity of import declarations and load a module conditionally or on demand. The following are some reasons why you might need to use dynamic import:
- When importing statically significantly slows the loading of your code or increases your program's memory usage, and there is a low likelihood that you will need the code you are importing, or you will not need it until a later time.
- When the module you are importing does not exist at load time.
- When the import specifier string needs to be constructed dynamically. (Static import only supports static specifiers.)
- When the module being imported has side effects, and you do not want those side effects unless some condition is true. (It is recommended not to have any side effects in a module, but you sometimes cannot control this in your module dependencies.)
- When you are in a non-module environment (for example, `eval` or a script file).
Use dynamic import only when necessary. The static form is preferable for loading initial dependencies, and can benefit more readily from static analysis tools and [tree shaking](/en-US/docs/Glossary/Tree_shaking).
If your file is not run as a module (if it's referenced in an HTML file, the script tag must have `type="module"`), you will not be able to use static import declarations, but the asynchronous dynamic import syntax will always be available, allowing you to import modules into non-module environments.
Dynamic module import is not permitted in all execution contexts.
For example, `import()` can be used in the main thread, a shared worker, or a dedicated worker, but will throw if called within a [service worker](/en-US/docs/Web/API/Service_Worker_API) or a [worklet](/en-US/docs/Web/API/Worklet).
### Module namespace object
A _module namespace object_ is an object that describes all exports from a module. It is a static object that is created when the module is evaluated. There are two ways to access the module namespace object of a module: through a [namespace import](/en-US/docs/Web/JavaScript/Reference/Statements/import#namespace_import) (`import * as name from moduleName`), or through the fulfillment value of a dynamic import.
The module namespace object 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). This means all string keys of the object correspond to the exports of the module and there are never extra keys. All keys are [enumerable](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) in lexicographic order (i.e. the default behavior of [`Array.prototype.sort()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#description)), with the default export available as a key called `default`. In addition, the module namespace object has a [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property with the value `"Module"`, used in {{jsxref("Object.prototype.toString()")}}.
The string properties are non-configurable and writable when you use {{jsxref("Object.getOwnPropertyDescriptors()")}} to get their descriptors. However, they are effectively read-only, because you cannot re-assign a property to a new value. This behavior mirrors the fact that static imports create "[live bindings](/en-US/docs/Web/JavaScript/Reference/Statements/import#imported_values_can_only_be_modified_by_the_exporter)" β the values can be re-assigned by the module exporting them, but not by the module importing them. The writability of the properties reflects the possibility of the values changing, because non-configurable and non-writable properties must be constant. For example, you can re-assign the exported value of a variable, and the new value can be observed in the module namespace object.
Each module specifier corresponds to a unique module namespace object, so the following is generally true:
```js
import * as mod from "/my-module.js";
import("/my-module.js").then((mod2) => {
console.log(mod === mod2); // true
});
```
Except in one curious case: because a promise never fulfills to a [thenable](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables), if the `my-module.js` module exports a function called `then()`, that function will automatically get called when the dynamic import's promise is fulfilled, as part of the [promise resolution](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolve_function) process.
```js
// my-module.js
export function then(resolve) {
console.log("then() called");
resolve(1);
}
```
```js
// main.js
import * as mod from "/my-module.js";
import("/my-module.js").then((mod2) => {
// Logs "then() called"
console.log(mod === mod2); // false
});
```
> **Warning:** Do not export a function called `then()` from a module. This will cause the module to behave differently when imported dynamically than when imported statically.
## Examples
### Import a module for its side effects only
```js
(async () => {
if (somethingIsTrue) {
// import module for side effects
await import("/modules/my-module.js");
}
})();
```
If your project uses packages that export ESM, you can also import them for side
effects only. This will run the code in the package entry point file (and any files it
imports) only.
### Importing defaults
You need to destructure and rename the "default" key from the returned object.
```js
(async () => {
if (somethingIsTrue) {
const {
default: myDefault,
foo,
bar,
} = await import("/modules/my-module.js");
}
})();
```
### Importing on-demand in response to user action
This example shows how to load functionality on to a page based on a user action, in this case a button click, and then call a function within that module. This is not the only way to implement this functionality. The `import()` function also supports `await`.
```js
const main = document.querySelector("main");
for (const link of document.querySelectorAll("nav > a")) {
link.addEventListener("click", (e) => {
e.preventDefault();
import("/modules/my-module.js")
.then((module) => {
module.loadPageInto(main);
})
.catch((err) => {
main.textContent = err.message;
});
});
}
```
### Importing different modules based on environment
In processes such as server-side rendering, you may need to load different logic on server or in browser because they interact with different globals or modules (for example, browser code has access to web APIs like `document` and `navigator`, while server code has access to the server file system). You can do so through a conditional dynamic import.
```js
let myModule;
if (typeof window === "undefined") {
myModule = await import("module-used-on-server");
} else {
myModule = await import("module-used-in-browser");
}
```
### Importing modules with a non-literal specifier
Dynamic imports allow any expression as the module specifier, not necessarily string literals.
Here, we load 10 modules, `/modules/module-0.js`, `/modules/module-1.js`, etc., concurrently, and call the `load` functions that each one exports.
```js
Promise.all(
Array.from({ length: 10 }).map(
(_, index) => import(`/modules/module-${index}.js`),
),
).then((modules) => modules.forEach((module) => module.load()));
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`import`](/en-US/docs/Web/JavaScript/Reference/Statements/import)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/grouping/index.md | ---
title: Grouping operator ( )
slug: Web/JavaScript/Reference/Operators/Grouping
page-type: javascript-operator
browser-compat: javascript.operators.grouping
---
{{jsSidebar("Operators")}}
The **grouping `( )`** operator controls the precedence of evaluation in expressions. It also acts as a container for arbitrary expressions in certain syntactic constructs, where ambiguity or syntax errors would otherwise occur.
{{EmbedInteractiveExample("pages/js/expressions-groupingoperator.html")}}
## Syntax
```js-nolint
(expression)
```
### Parameters
- `expression`
- : Any [expression](/en-US/docs/Web/JavaScript/Reference/Operators) to be evaluated, including [comma-joined](/en-US/docs/Web/JavaScript/Reference/Operators/Comma_operator) expressions.
## Description
The grouping operator consists of a pair of parentheses around an expression that groups the contents. The operator overrides the normal [operator precedence](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence), so that operators with lower precedence (as low as the [comma](/en-US/docs/Web/JavaScript/Reference/Operators/Comma_operator) operator) can be evaluated before an operator with higher precedence.
## Examples
### Using the grouping operator
Evaluating addition and subtraction before multiplication and division.
```js-nolint
const a = 1;
const b = 2;
const c = 3;
// default precedence
a + b * c; // 7
// evaluated by default like this
a + (b * c); // 7
// now overriding precedence
// addition before multiplication
(a + b) * c; // 9
// which is equivalent to
a * c + b * c; // 9
```
Notice in these examples that the order in which the _operators_ evaluate has changed, but the order in which the _operands_ evaluate has not. For example, in this code, the function invocations `a()`, `b()`, and `c()` are evaluated left-to-right (the normal order of evaluation) before the operator order is considered.
```js
a() * (b() + c());
```
The function `a` will be called before the function `b`, which will be called before the function `c`. For more on operator precedence, see its [reference page](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence).
### Using the grouping operator to eliminate parsing ambiguity
An [expression statement](/en-US/docs/Web/JavaScript/Reference/Statements/Expression_statement) cannot start with the keyword `function`, because the parser would see it as the start of a [function declaration](/en-US/docs/Web/JavaScript/Reference/Statements/function). This means the following [IIFE](/en-US/docs/Glossary/IIFE) syntax is invalid:
```js-nolint example-bad
function () {
// code
}();
```
The grouping operator can be used to eliminate this ambiguity, since when the parser sees the left parenthesis, it knows that what follows must be an expression instead of a declaration.
```js
(function () {
// code
})();
```
You may also use the [`void`](/en-US/docs/Web/JavaScript/Reference/Operators/void#immediately_invoked_function_expressions) operator to eliminate ambiguity.
In an [arrow function](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) expression body (one that directly returns an expression without the keyword `return`), the grouping operator can be used to return an object literal expression, because otherwise the left curly brace would be interpreted as the start of the function body.
```js
const f = () => ({ a: 1 });
```
If a property is accessed on a number literal, the [property accessor](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors) dot `.` may be ambiguous with a decimal point, unless the number already has a decimal point. You can wrap integer literals in parentheses to eliminate this ambiguity.
```js
(1).toString(); // "1"
```
<!-- TODO in the future we can add a decorator section -->
### Grouping operator and automatic semicolon insertion
The grouping operator can mitigate [automatic semicolon insertion](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#automatic_semicolon_insertion) (ASI) pitfalls. For example, the `return` keyword and the returned expression cannot have a line break in between:
```js-nolint example-bad
function sum(a, b) {
return
a + b;
}
```
This code will return `undefined`, because a semicolon is inserted directly after the `return` keyword, which causes the function to return immediately without evaluating `a + b`. In case the returned expression is long and you want to keep it well-formatted, you may use the grouping operator to signify that the `return` keyword is followed by an expression and prevent semicolon insertion:
```js-nolint example-good
function sum(a, b) {
return (
a + b
);
}
```
However, grouping may also _introduce_ ASI hazards. When a line starts with a left parenthesis and the previous line ends with an expression, the parser will not insert a semicolon before the line break, because it could be the middle of a function call. For example:
```js-nolint example-bad
const a = 1
(1).toString()
```
This code would be parsed as:
```js
const a = 1(1).toString();
```
Which throws "TypeError: 1 is not a function". If your coding style does not use semicolons, remember that when a line starts with a left parenthesis, _prefix_ it with a semicolon. This practice is recommended by several formatters and/or style guides, including [Prettier](https://prettier.io/docs/en/rationale.html#semicolons) and [standard](https://standardjs.com/rules.html#semicolons).
```js-nolint example-good
const a = 1
;(1).toString()
```
For more advice on working with ASI, see its [reference section](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#automatic_semicolon_insertion).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Operator precedence](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence)
- {{jsxref("Operators/delete", "delete")}}
- {{jsxref("Operators/typeof", "typeof")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/greater_than/index.md | ---
title: Greater than (>)
slug: Web/JavaScript/Reference/Operators/Greater_than
page-type: javascript-operator
browser-compat: javascript.operators.greater_than
---
{{jsSidebar("Operators")}}
The **greater than (`>`)** operator returns `true` if the left
operand is greater than the right operand, and `false` otherwise.
{{EmbedInteractiveExample("pages/js/expressions-greater-than.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, except the two operands are swapped. `x > y` is generally equivalent to `y < x`, except that `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.
## Examples
### String to string comparison
```js
"a" > "b"; // false
"a" > "a"; // false
"a" > "3"; // true
```
### String to number comparison
```js
"5" > 3; // true
"3" > 3; // false
"3" > 5; // false
"hello" > 5; // false
5 > "hello"; // false
"5" > 3n; // true
"3" > 5n; // false
```
### Number to Number comparison
```js
5 > 3; // true
3 > 3; // false
3 > 5; // false
```
### Number to BigInt comparison
```js
5n > 3; // true
3 > 5n; // false
```
### Comparing Boolean, null, undefined, NaN
```js
true > false; // true
false > true; // false
true > 0; // true
true > 1; // false
null > 0; // false
1 > null; // true
undefined > 3; // false
3 > undefined; // false
3 > NaN; // false
NaN > 3; // false
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [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)
- [Less than or equal (`<=`)](/en-US/docs/Web/JavaScript/Reference/Operators/Less_than_or_equal)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/division/index.md | ---
title: Division (/)
slug: Web/JavaScript/Reference/Operators/Division
page-type: javascript-operator
browser-compat: javascript.operators.division
---
{{jsSidebar("Operators")}}
The **division (`/`)** operator produces the quotient of its operands where the left operand is the dividend and the right operand is the divisor.
{{EmbedInteractiveExample("pages/js/expressions-division.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 division if both operands become BigInts; otherwise, it performs number division. A {{jsxref("TypeError")}} is thrown if one operand becomes a BigInt but the other becomes a number.
For BigInt division, the result is the quotient of the two operands truncated towards zero, and the remainder is discarded. A {{jsxref("RangeError")}} is thrown if the divisor `y` is `0n`. This is because number division by zero returns `Infinity` or `-Infinity`, but BigInt has no concept of infinity.
## Examples
### Basic division
```js
1 / 2; // 0.5
Math.floor(3 / 2); // 1
1.0 / 2.0; // 0.5
1n / 2n; // 0n
5n / 3n; // 1n
-1n / 3n; // 0n
1n / -3n; // 0n
2n / 2; // TypeError: Cannot mix BigInt and other types, use explicit conversions
// To do division with a BigInt and a non-BigInt, convert either operand
2n / BigInt(2); // 1n
Number(2n) / 2; // 1
```
### Division by zero
```js
2.0 / 0; // Infinity
2.0 / 0.0; // Infinity, because 0.0 === 0
2.0 / -0.0; // -Infinity
2n / 0n; // RangeError: Division by zero
```
## 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)
- [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)
- [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)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/nullish_coalescing/index.md | ---
title: Nullish coalescing operator (??)
slug: Web/JavaScript/Reference/Operators/Nullish_coalescing
page-type: javascript-operator
browser-compat: javascript.operators.nullish_coalescing
---
{{jsSidebar("Operators")}}
The **nullish coalescing (`??`)** operator is a logical
operator that returns its right-hand side operand when its left-hand side operand is
[`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) or {{jsxref("undefined")}}, and otherwise returns its left-hand side
operand.
{{EmbedInteractiveExample("pages/js/expressions-nullishcoalescingoperator.html")}}
## Syntax
```js-nolint
leftExpr ?? rightExpr
```
## Description
The nullish coalescing operator can be seen as a special case of the [logical OR (`||`) operator](/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR). The latter returns the right-hand side operand if the left operand is _any_ {{Glossary("falsy")}} value, not only `null` or `undefined`. In other words, if you use `||` to provide some default value to another variable `foo`, you may encounter unexpected behaviors if you consider some falsy values as usable (e.g., `''` or `0`). See [below](#assigning_a_default_value_to_a_variable) for more examples.
The nullish coalescing operator has the fifth-lowest [operator precedence](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence), directly lower than `||` and directly higher than the [conditional (ternary) operator](/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator).
It is not possible to combine both the AND (`&&`) and OR operators (`||`) directly with `??`. A [syntax error](/en-US/docs/Web/JavaScript/Reference/Errors/Cant_use_nullish_coalescing_unparenthesized) will be thrown in such cases.
```js-nolint example-bad
null || undefined ?? "foo"; // raises a SyntaxError
true && undefined ?? "foo"; // raises a SyntaxError
```
Instead, provide parenthesis to explicitly indicate precedence:
```js example-good
(null || undefined) ?? "foo"; // returns "foo"
```
## Examples
### Using the nullish coalescing operator
In this example, we will provide default values but keep values other than `null` or `undefined`.
```js
const nullValue = null;
const emptyText = ""; // falsy
const someNumber = 42;
const valA = nullValue ?? "default for A";
const valB = emptyText ?? "default for B";
const valC = someNumber ?? 0;
console.log(valA); // "default for A"
console.log(valB); // "" (as the empty string is not null or undefined)
console.log(valC); // 42
```
### Assigning a default value to a variable
Earlier, when one wanted to assign a default value to a variable, a common pattern was to use the logical OR operator ([`||`](/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR)):
```js
let foo;
// foo is never assigned any value so it is still undefined
const someDummyText = foo || "Hello!";
```
However, due to `||` being a boolean logical operator, the left-hand-side operand was coerced to a boolean for the evaluation and any _falsy_ value (including `0`, `''`, `NaN`, `false`, etc.) was not returned. This behavior may cause unexpected consequences if you consider `0`, `''`, or `NaN` as valid values.
```js
const count = 0;
const text = "";
const qty = count || 42;
const message = text || "hi!";
console.log(qty); // 42 and not 0
console.log(message); // "hi!" and not ""
```
The nullish coalescing operator avoids this pitfall by only returning the second operand when the first one evaluates to either `null` or `undefined` (but no other falsy values):
```js
const myText = ""; // An empty string (which is also a falsy value)
const notFalsyText = myText || "Hello world";
console.log(notFalsyText); // Hello world
const preservingFalsy = myText ?? "Hi neighborhood";
console.log(preservingFalsy); // '' (as myText is neither undefined nor null)
```
### Short-circuiting
Like the OR and AND logical operators, the right-hand side expression is not evaluated if the left-hand side proves to be neither `null` nor `undefined`.
```js
function a() {
console.log("a was called");
return undefined;
}
function b() {
console.log("b was called");
return false;
}
function c() {
console.log("c was called");
return "foo";
}
console.log(a() ?? c());
// Logs "a was called" then "c was called" and then "foo"
// as a() returned undefined so both expressions are evaluated
console.log(b() ?? c());
// Logs "b was called" then "false"
// as b() returned false (and not null or undefined), the right
// hand side expression was not evaluated
```
### Relationship with the optional chaining operator (?.)
The nullish coalescing operator treats `undefined` and `null` as specific values. So does the [optional chaining operator (`?.`)](/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining), which is useful to access a property of an object which may be `null` or `undefined`. Combining them, you can safely access a property of an object which may be nullish and provide a default value if it is.
```js
const foo = { someFooProp: "hi" };
console.log(foo.someFooProp?.toUpperCase() ?? "not available"); // "HI"
console.log(foo.someBarProp?.toUpperCase() ?? "not available"); // "not available"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Nullish coalescing assignment (`??=`)](/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_assignment)
- [Optional chaining (`?.`)](/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)
- [Logical OR (`||`)](/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR)
- [Default parameters](/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/logical_and/index.md | ---
title: Logical AND (&&)
slug: Web/JavaScript/Reference/Operators/Logical_AND
page-type: javascript-operator
browser-compat: javascript.operators.logical_and
---
{{jsSidebar("Operators")}}
The **logical AND (`&&`)** (logical conjunction) operator for a set of boolean operands will be `true` if and only if all the operands are `true`. Otherwise it will be `false`.
More generally, the operator returns the value of the first {{Glossary("falsy")}} operand encountered when evaluating from left to right, or the value of the last operand if they are all {{Glossary("truthy")}}.
{{EmbedInteractiveExample("pages/js/expressions-logical-and.html", "shorter")}}
## Syntax
```js-nolint
x && y
```
## Description
Logical AND (`&&`) evaluates operands from left to right, returning immediately with the value of the first {{Glossary("falsy")}} operand it encounters; if all values are {{Glossary("truthy")}}, the value of the last operand is returned.
If a value can be converted to `true`, the value is so-called {{Glossary("truthy")}}. If a value can be converted to `false`, the value is so-called {{Glossary("falsy")}}.
Examples of expressions that can be converted to false are:
- `false`;
- `null`;
- `NaN`;
- `0`;
- empty string (`""` or `''` or ` `` `);
- `undefined`.
The AND operator preserves non-Boolean values and returns them as they are:
```js
result = "" && "foo"; // result is assigned "" (empty string)
result = 2 && 0; // result is assigned 0
result = "foo" && 4; // result is assigned 4
```
Even though the `&&` operator can be used with non-Boolean operands, it is still considered a boolean operator since its return value can always be
converted to a [boolean primitive](/en-US/docs/Web/JavaScript/Data_structures#boolean_type).
To explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double [`NOT operator`](/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT) or the {{jsxref("Boolean/Boolean", "Boolean")}} constructor.
### Short-circuit evaluation
The logical AND expression is a short-circuit operator.
As each operand is converted to a boolean, if the result of one conversion is found to be `false`, the AND operator stops and returns the original value of that falsy operand; it does **not** evaluate any of the remaining operands.
Consider the pseudocode below.
```plain
(some falsy expression) && expr
```
The `expr` part is **never evaluated** because the first operand `(some falsy expression)` is evaluated as {{Glossary("falsy")}}.
If `expr` is a function, the function is never called.
See the example below:
```js
function A() {
console.log("called A");
return false;
}
function B() {
console.log("called B");
return true;
}
console.log(A() && B());
// Logs "called A" to the console due to the call for function A,
// && evaluates to false (function A returns false), then false is logged to the console;
// the AND operator short-circuits here and ignores function B
```
### Operator precedence
The AND operator has a higher precedence than the OR operator, meaning the `&&` operator is executed before the `||` operator (see [operator precedence](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence)).
```js-nolint
true || false && false; // true
true && (false || false); // false
(2 === 3) || (4 < 0) && (1 === 1); // false
```
## Examples
### Using AND
The following code shows examples of the `&&` (logical AND)
operator.
```js
a1 = true && true; // t && t returns true
a2 = true && false; // t && f returns false
a3 = false && true; // f && t returns false
a4 = false && 3 === 4; // f && f returns false
a5 = "Cat" && "Dog"; // t && t returns "Dog"
a6 = false && "Cat"; // f && t returns false
a7 = "Cat" && false; // t && f returns false
a8 = "" && false; // f && f returns ""
a9 = false && ""; // f && f returns false
```
### Conversion rules for booleans
#### Converting AND to OR
The following operation involving **booleans**:
```js-nolint
bCondition1 && bCondition2
```
is always equal to:
```js-nolint
!(!bCondition1 || !bCondition2)
```
#### Converting OR to AND
The following operation involving **booleans**:
```js-nolint
bCondition1 || bCondition2
```
is always equal to:
```js-nolint
!(!bCondition1 && !bCondition2)
```
### Removing nested parentheses
As logical expressions are evaluated left to right, it is always possible to remove parentheses from a complex expression provided that certain rules are followed.
The following composite operation involving **booleans**:
```js-nolint
bCondition1 || (bCondition2 && bCondition3)
```
is always equal to:
```js-nolint
bCondition1 || bCondition2 && bCondition3
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Boolean")}}
- {{Glossary("Truthy")}}
- {{Glossary("Falsy")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/division_assignment/index.md | ---
title: Division assignment (/=)
slug: Web/JavaScript/Reference/Operators/Division_assignment
page-type: javascript-operator
browser-compat: javascript.operators.division_assignment
---
{{jsSidebar("Operators")}}
The **division assignment (`/=`)** operator performs [division](/en-US/docs/Web/JavaScript/Reference/Operators/Division) on the two operands and assigns the result to the left operand.
{{EmbedInteractiveExample("pages/js/expressions-division-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 division assignment
```js
let bar = 5;
bar /= 2; // 2.5
bar /= 2; // 1.25
bar /= 0; // Infinity
bar /= "foo"; // NaN
let foo = 3n;
foo /= 2n; // 1n
foo /= 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)
- [Division (`/`)](/en-US/docs/Web/JavaScript/Reference/Operators/Division)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/equality/index.md | ---
title: Equality (==)
slug: Web/JavaScript/Reference/Operators/Equality
page-type: javascript-operator
browser-compat: javascript.operators.equality
---
{{jsSidebar("Operators")}}
The **equality (`==`)** operator checks whether its two operands are equal,
returning a Boolean result.
Unlike the [strict equality](/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality) operator,
it attempts to convert and compare operands that are of different types.
{{EmbedInteractiveExample("pages/js/expressions-equality.html")}}
## Syntax
```js-nolint
x == y
```
## Description
The equality operators (`==` and `!=`) provide the [IsLooselyEqual](/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#loose_equality_using) semantic. This can be roughly summarized as follows:
1. If the operands have the same type, they are compared as follows:
- Object: return `true` only if both operands reference the same object.
- String: return `true` only if both operands have the same characters in the same order.
- Number: return `true` only if both operands have the same value. `+0` and `-0` are treated as the same value. If either operand is `NaN`, return `false`; so, `NaN` is never equal to `NaN`.
- Boolean: return `true` only if operands are both `true` or both `false`.
- BigInt: return `true` only if both operands have the same value.
- Symbol: return `true` only if both operands reference the same symbol.
2. If one of the operands is `null` or `undefined`, the other must also be `null` or `undefined` to return `true`. Otherwise return `false`.
3. If one of the operands is an object and the other is a primitive, [convert the object to a primitive](/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion).
4. At this step, both operands are converted to primitives (one of String, Number, Boolean, Symbol, and BigInt). The rest of the conversion is done case-by-case.
- If they are of the same type, compare them using step 1.
- If one of the operands is a Symbol but the other is not, return `false`.
- If one of the operands is a Boolean but the other is not, [convert the boolean to a number](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion): `true` is converted to 1, and `false` is converted to 0. Then compare the two operands loosely again.
- Number to String: [convert the string to a number](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion). Conversion failure results in `NaN`, which will guarantee the equality to be `false`.
- Number to BigInt: compare by their numeric value. If the number is Β±Infinity or `NaN`, return `false`.
- String to BigInt: convert the string to a BigInt using the same algorithm as the [`BigInt()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/BigInt) constructor. If conversion fails, return `false`.
Loose equality is _symmetric_: `A == B` always has identical semantics to `B == A` for any values of `A` and `B` (except for the order of applied conversions).
The most notable difference between this operator and the [strict equality](/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality) (`===`) operator is that the strict equality operator does not attempt type conversion. Instead, the strict equality operator always considers operands of different types to be different. The strict equality operator essentially carries out only step 1, and then returns `false` for all other cases.
There's a "willful violation" of the above algorithm: if one of the operands is [`document.all`](/en-US/docs/Web/API/Document/all), it is treated as if it's `undefined`. This means that `document.all == null` is `true`, but `document.all === undefined && document.all === null` is `false`.
## Examples
### Comparison with no type conversion
```js
1 == 1; // true
"hello" == "hello"; // true
```
### Comparison with type conversion
```js
"1" == 1; // true
1 == "1"; // true
0 == false; // true
0 == null; // false
0 == undefined; // false
0 == !!null; // true, look at Logical NOT operator
0 == !!undefined; // true, look at Logical NOT operator
null == undefined; // true
const number1 = new Number(3);
const number2 = new Number(3);
number1 == 3; // true
number1 == number2; // false
```
### Comparison of objects
```js
const object1 = {
key: "value",
};
const object2 = {
key: "value",
};
console.log(object1 == object2); // false
console.log(object1 == object1); // true
```
### Comparing strings and String objects
Note that strings constructed using `new String()` are objects. If you
compare one of these with a string literal, the `String` object will be
converted to a string literal and the contents will be compared. However, if both
operands are `String` objects, then they are compared as objects and must
reference the same object for comparison to succeed:
```js
const string1 = "hello";
const string2 = String("hello");
const string3 = new String("hello");
const string4 = new String("hello");
console.log(string1 == string2); // true
console.log(string1 == string3); // true
console.log(string2 == string3); // true
console.log(string3 == string4); // false
console.log(string4 == string4); // true
```
### Comparing Dates and strings
```js
const d = new Date("1995-12-17T03:24:00");
const s = d.toString(); // for example: "Sun Dec 17 1995 03:24:00 GMT-0800 (Pacific Standard Time)"
console.log(d == s); //true
```
### Comparing arrays and strings
```js
const a = [1, 2, 3];
const b = "1,2,3";
a == b; // true, `a` converts to string
const c = [true, 0.5, "hey"];
const d = c.toString(); // "true,0.5,hey"
c == d; // true
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Inequality (`!=`)](/en-US/docs/Web/JavaScript/Reference/Operators/Inequality)
- [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/instanceof/index.md | ---
title: instanceof
slug: Web/JavaScript/Reference/Operators/instanceof
page-type: javascript-operator
browser-compat: javascript.operators.instanceof
---
{{jsSidebar("Operators")}}
The **`instanceof`** operator tests to see if the `prototype` property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value. Its behavior can be customized with [`Symbol.hasInstance`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance).
{{EmbedInteractiveExample("pages/js/expressions-instanceof.html")}}
## Syntax
```js-nolint
object instanceof constructor
```
### Parameters
- `object`
- : The object to test.
- `constructor`
- : Constructor to test against.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if `constructor` is not an object. If `constructor` doesn't have a [`@@hasInstance`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance) method, it must also be a function.
## Description
The `instanceof` operator tests the presence of `constructor.prototype` in `object`'s prototype chain. This usually (though [not always](#overriding_the_behavior_of_instanceof)) means `object` was constructed with `constructor`.
```js
// defining constructors
function C() {}
function D() {}
const o = new C();
// true, because: Object.getPrototypeOf(o) === C.prototype
o instanceof C;
// false, because D.prototype is nowhere in o's prototype chain
o instanceof D;
o instanceof Object; // true, because:
C.prototype instanceof Object; // true
// Re-assign `constructor.prototype`: you should
// rarely do this in practice.
C.prototype = {};
const o2 = new C();
o2 instanceof C; // true
// false, because C.prototype is nowhere in
// o's prototype chain anymore
o instanceof C;
D.prototype = new C(); // add C to [[Prototype]] linkage of D
const o3 = new D();
o3 instanceof D; // true
o3 instanceof C; // true since C.prototype is now in o3's prototype chain
```
Note that the value of an `instanceof` test can change if `constructor.prototype` is re-assigned after creating the object (which is usually discouraged). It can also be changed by changing `object`'s prototype using [`Object.setPrototypeOf`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf).
Classes behave in the same way, because classes also have the `prototype` property.
```js
class A {}
class B extends A {}
const o1 = new A();
// true, because Object.getPrototypeOf(o1) === A.prototype
o1 instanceof A;
// false, because B.prototype is nowhere in o1's prototype chain
o1 instanceof B;
const o2 = new B();
// true, because Object.getPrototypeOf(Object.getPrototypeOf(o2)) === A.prototype
o2 instanceof A;
// true, because Object.getPrototypeOf(o2) === B.prototype
o2 instanceof B;
```
For [bound functions](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind), `instanceof` looks up for the `prototype` property on the target function, since bound functions don't have `prototype`.
```js
class Base {}
const BoundBase = Base.bind(null, 1, 2);
console.log(new Base() instanceof BoundBase); // true
```
### instanceof and @@hasInstance
If `constructor` has a [`Symbol.hasInstance`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance) method, the method will be called in priority, with `object` as its only argument and `constructor` as `this`.
```js
// This class allows plain objects to be disguised as this class's instance,
// as long as the object has a particular flag as its property.
class Forgeable {
static isInstanceFlag = Symbol("isInstanceFlag");
static [Symbol.hasInstance](obj) {
return Forgeable.isInstanceFlag in obj;
}
}
const obj = { [Forgeable.isInstanceFlag]: true };
console.log(obj instanceof Forgeable); // true
```
Because all functions inherit from `Function.prototype` by default, most of the time, the [`Function.prototype[@@hasInstance]`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/@@hasInstance) method specifies the behavior of `instanceof` when the right-hand side is a function. See the {{jsxref("Symbol.hasInstance")}} page for the exact algorithm of `instanceof`.
### instanceof and multiple realms
JavaScript execution environments (windows, frames, etc.) are each in their own _realm_. This means that they have different built-ins (different global object, different constructors, etc.). This may result in unexpected results. For instance, `[] instanceof window.frames[0].Array` will return `false`, because `Array.prototype !== window.frames[0].Array.prototype` and arrays in the current realm inherit from the former.
This may not make sense at first, but for scripts dealing with multiple frames or windows, and passing objects from one context to another via functions, this will be a valid and strong issue. For instance, you can securely check if a given object is in fact an Array using {{jsxref("Array.isArray()")}}, neglecting which realm it comes from.
For example, to check if a [`Node`](/en-US/docs/Web/API/Node) is an [`SVGElement`](/en-US/docs/Web/API/SVGElement) in a different context, you can use `myNode instanceof myNode.ownerDocument.defaultView.SVGElement`.
## Examples
### Using instanceof with String
The following example shows the behavior of `instanceof` with `String` objects.
```js
const literalString = "This is a literal string";
const stringObject = new String("String created with constructor");
literalString instanceof String; // false, string primitive is not a String
stringObject instanceof String; // true
literalString instanceof Object; // false, string primitive is not an Object
stringObject instanceof Object; // true
stringObject instanceof Date; // false
```
### Using instanceof with Date
The following example shows the behavior of `instanceof` with `Date` objects.
```js
const myDate = new Date();
myDate instanceof Date; // true
myDate instanceof Object; // true
myDate instanceof String; // false
```
### Objects created using Object.create()
The following example shows the behavior of `instanceof` with objects created using {{jsxref("Object.create()")}}.
```js
function Shape() {}
function Rectangle() {
Shape.call(this); // call super constructor.
}
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
const rect = new Rectangle();
rect instanceof Object; // true
rect instanceof Shape; // true
rect instanceof Rectangle; // true
rect instanceof String; // false
const literalObject = {};
const nullObject = Object.create(null);
nullObject.name = "My object";
literalObject instanceof Object; // true, every object literal has Object.prototype as prototype
({}) instanceof Object; // true, same case as above
nullObject instanceof Object; // false, prototype is end of prototype chain (null)
```
### Demonstrating that mycar is of type Car and type Object
The following code creates an object type `Car` and an instance of that object type, `mycar`. The `instanceof` operator demonstrates that the `mycar` object is of type `Car` and of type `Object`.
```js
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
const mycar = new Car("Honda", "Accord", 1998);
const a = mycar instanceof Car; // returns true
const b = mycar instanceof Object; // returns true
```
### Not an instanceof
To test if an object is not an `instanceof` a specific constructor, you can do:
```js
if (!(mycar instanceof Car)) {
// Do something, like:
// mycar = new Car(mycar)
}
```
This is really different from:
```js-nolint example-bad
if (!mycar instanceof Car) {
// unreachable code
}
```
This will always be `false`. (`!mycar` will be evaluated before `instanceof`, so you always try to know if a boolean is an instance of `Car`).
### Overriding the behavior of instanceof
A common pitfall of using `instanceof` is believing that, if `x instanceof C`, then `x` was created using `C` as constructor. This is not true, because `x` could be directly assigned with `C.prototype` as its prototype. In this case, if your code reads [private fields](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties) of `C` from `x`, it would still fail:
```js
class C {
#value = "foo";
static getValue(x) {
return x.#value;
}
}
const x = { __proto__: C.prototype };
if (x instanceof C) {
console.log(C.getValue(x)); // TypeError: Cannot read private member #value from an object whose class did not declare it
}
```
To avoid this, you can override the behavior of `instanceof` by adding a `Symbol.hasInstance` method to `C`, so that it does a branded check with [`in`](/en-US/docs/Web/JavaScript/Reference/Operators/in):
```js
class C {
#value = "foo";
static [Symbol.hasInstance](x) {
return #value in x;
}
static getValue(x) {
return x.#value;
}
}
const x = { __proto__: C.prototype };
if (x instanceof C) {
// Doesn't run, because x is not a C
console.log(C.getValue(x));
}
```
Note that you may want to limit this behavior to the current class; otherwise, it could lead to false positives for subclasses:
```js
class D extends C {}
console.log(new C() instanceof D); // true; because D inherits @@hasInstance from C
```
You could do this by checking that `this` is the current constructor:
```js
class C {
#value = "foo";
static [Symbol.hasInstance](x) {
return this === C && #value in x;
}
}
class D extends C {}
console.log(new C() instanceof D); // false
console.log(new C() instanceof C); // true
console.log({ __proto__: C.prototype } instanceof C); // false
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`typeof`](/en-US/docs/Web/JavaScript/Reference/Operators/typeof)
- {{jsxref("Symbol.hasInstance")}}
- {{jsxref("Object.prototype.isPrototypeOf")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/super/index.md | ---
title: super
slug: Web/JavaScript/Reference/Operators/super
page-type: javascript-language-feature
browser-compat: javascript.operators.super
---
{{jsSidebar("Operators")}}
The **`super`** keyword is used to access properties on an object literal or class's [[Prototype]], or invoke a superclass's constructor.
The `super.prop` and `super[expr]` expressions are valid in any [method definition](/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions) in both [classes](/en-US/docs/Web/JavaScript/Reference/Classes) and [object literals](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer). The `super(...args)` expression is valid in class constructors.
{{EmbedInteractiveExample("pages/js/expressions-super.html", "taller")}}
## Syntax
```js-nolint
super([arguments]) // calls the parent constructor.
super.propertyOnParent
super[expression]
```
## Description
The `super` keyword can be used in two ways: as a "function call" (`super(...args)`), or as a "property lookup" (`super.prop` and `super[expr]`).
> **Note:** `super` is a keyword and these are special syntactic constructs. `super` is not a variable that points to the prototype object. Attempting to read `super` itself is a {{jsxref("SyntaxError")}}.
>
> ```js-nolint example-bad
> const child = {
> myParent() {
> console.log(super); // SyntaxError: 'super' keyword unexpected here
> },
> };
> ```
In the [constructor](/en-US/docs/Web/JavaScript/Reference/Classes/constructor) body of a derived class (with `extends`), the `super` keyword may appear as a "function call" (`super(...args)`), which must be called before the `this` keyword is used, and before the constructor returns. It calls the parent class's constructor and binds the parent class's public fields, after which the derived class's constructor can further access and modify `this`.
The "property lookup" form can be used to access methods and properties of an object literal's or class's [[Prototype]]. Within a class's body, the reference of `super` can be either the superclass's constructor itself, or the constructor's `prototype`, depending on whether the execution context is instance creation or class initialization. See the Examples section for more details.
Note that the reference of `super` is determined by the class or object literal `super` was declared in, not the object the method is called on. Therefore, unbinding or re-binding a method doesn't change the reference of `super` in it (although they do change the reference of [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this)). You can see `super` as a variable in the class or object literal scope, which the methods create a closure over. (But also beware that it's not actually a variable, as explained above.)
When setting properties through `super`, the property is set on `this` instead.
## Examples
### Using super in classes
This code snippet is taken from the [classes sample](https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html) ([live demo](https://googlechrome.github.io/samples/classes-es6/index.html)). Here `super()` is called to avoid duplicating the constructor parts' that are common between `Rectangle` and `Square`.
```js
class Rectangle {
constructor(height, width) {
this.name = "Rectangle";
this.height = height;
this.width = width;
}
sayName() {
console.log(`Hi, I am a ${this.name}.`);
}
get area() {
return this.height * this.width;
}
set area(value) {
this._area = value;
}
}
class Square extends Rectangle {
constructor(length) {
// Here, it calls the parent class's constructor with lengths
// provided for the Rectangle's width and height
super(length, length);
// Note: In derived classes, super() must be called before you
// can use 'this'. Moving this to the top causes a ReferenceError.
this.name = "Square";
}
}
```
### Super-calling static methods
You are also able to call super on [static](/en-US/docs/Web/JavaScript/Reference/Classes/static) methods.
```js
class Rectangle {
static logNbSides() {
return "I have 4 sides";
}
}
class Square extends Rectangle {
static logDescription() {
return `${super.logNbSides()} which are all equal`;
}
}
Square.logDescription(); // 'I have 4 sides which are all equal'
```
### Accessing super in class field declaration
`super` can also be accessed during class field initialization. The reference of `super` depends on whether the current field is an instance field or a static field.
```js
class Base {
static baseStaticField = 90;
baseMethod() {
return 10;
}
}
class Extended extends Base {
extendedField = super.baseMethod(); // 10
static extendedStaticField = super.baseStaticField; // 90
}
```
Note that instance fields are set on the instance instead of the constructor's `prototype`, so you can't use `super` to access the instance field of a superclass.
```js example-bad
class Base {
baseField = 10;
}
class Extended extends Base {
extendedField = super.baseField; // undefined
}
```
Here, `extendedField` is `undefined` instead of 10, because `baseField` is defined as an own property of the `Base` instance, instead of `Base.prototype`. `super`, in this context, only looks up properties on `Base.prototype`, because that's the [[Prototype]] of `Extended.prototype`.
### Deleting super properties will throw an error
You cannot use the [`delete` operator](/en-US/docs/Web/JavaScript/Reference/Operators/delete) and `super.prop` or `super[expr]` to delete a parent class' property β it will throw a {{jsxref("ReferenceError")}}.
```js
class Base {
foo() {}
}
class Derived extends Base {
delete() {
delete super.foo; // this is bad
}
}
new Derived().delete(); // ReferenceError: invalid delete involving 'super'.
```
### Using super.prop in object literals
Super can also be used in the [object initializer](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) notation. In this example, two objects define a method. In the second object, `super` calls the first object's method. This works with the help of {{jsxref("Object.setPrototypeOf()")}} with which we are able to set the prototype of `obj2` to `obj1`, so that `super` is able to find `method1` on `obj1`.
```js
const obj1 = {
method1() {
console.log("method 1");
},
};
const obj2 = {
method2() {
super.method1();
},
};
Object.setPrototypeOf(obj2, obj1);
obj2.method2(); // Logs "method 1"
```
### Methods that read super.prop do not behave differently when bound to other objects
Accessing `super.x` behaves like `Reflect.get(Object.getPrototypeOf(objectLiteral), "x", this)`, which means the property is always seeked on the object literal/class declaration's prototype, and unbinding and re-binding a method won't change the reference of `super`.
```js
class Base {
baseGetX() {
return 1;
}
}
class Extended extends Base {
getX() {
return super.baseGetX();
}
}
const e = new Extended();
console.log(e.getX()); // 1
const { getX } = e;
console.log(getX()); // 1
```
The same happens in object literals.
```js
const parent1 = { prop: 1 };
const parent2 = { prop: 2 };
const child = {
myParent() {
console.log(super.prop);
},
};
Object.setPrototypeOf(child, parent1);
child.myParent(); // Logs "1"
const myParent = child.myParent;
myParent(); // Still logs "1"
const anotherChild = { __proto__: parent2, myParent };
anotherChild.myParent(); // Still logs "1"
```
Only resetting the entire inheritance chain will change the reference of `super`.
```js
class Base {
baseGetX() {
return 1;
}
static staticBaseGetX() {
return 3;
}
}
class AnotherBase {
baseGetX() {
return 2;
}
static staticBaseGetX() {
return 4;
}
}
class Extended extends Base {
getX() {
return super.baseGetX();
}
static staticGetX() {
return super.staticBaseGetX();
}
}
const e = new Extended();
// Reset instance inheritance
Object.setPrototypeOf(Extended.prototype, AnotherBase.prototype);
console.log(e.getX()); // Logs "2" instead of "1", because the prototype chain has changed
console.log(Extended.staticGetX()); // Still logs "3", because we haven't modified the static part yet
// Reset static inheritance
Object.setPrototypeOf(Extended, AnotherBase);
console.log(Extended.staticGetX()); // Now logs "4"
```
### Calling methods from super
When calling `super.prop` as a function, the `this` value inside the `prop` function is the current `this`, not the object that `super` points to. For example, the `super.getName()` call logs `"Extended"`, despite the code looking like it's equivalent to `Base.getName()`.
```js
class Base {
static getName() {
console.log(this.name);
}
}
class Extended extends Base {
static getName() {
super.getName();
}
}
Extended.getName(); // Logs "Extended"
```
This is especially important when interacting with [static private properties](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties#private_static_fields).
### Setting super.prop sets the property on this instead
Setting properties of `super`, such as `super.x = 1`, behaves like `Reflect.set(Object.getPrototypeOf(objectLiteral), "x", 1, this)`. This is one of the cases where understanding `super` as simply "reference of the prototype object" falls short, because it actually sets the property on `this` instead.
```js
class A {}
class B extends A {
setX() {
super.x = 1;
}
}
const b = new B();
b.setX();
console.log(b); // B { x: 1 }
console.log(Object.hasOwn(b, "x")); // true
```
`super.x = 1` will look for the property descriptor of `x` on `A.prototype` (and invoke the setters defined there), but the `this` value will be set to `this`, which is `b` in this context. You can read [`Reflect.set`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/set) for more details on the case when `target` and `receiver` differ.
This means that while methods that _get_ `super.prop` are usually not susceptible to changes in the `this` context, those that _set_ `super.prop` are.
```js example-bad
/* Reusing same declarations as above */
const b2 = new B();
b2.setX.call(null); // TypeError: Cannot assign to read only property 'x' of object 'null'
```
However, `super.x = 1` still consults the property descriptor of the prototype object, which means you cannot rewrite non-writable properties, and setters will be invoked.
```js
class X {
constructor() {
// Create a non-writable property
Object.defineProperty(this, "prop", {
configurable: true,
writable: false,
value: 1,
});
}
}
class Y extends X {
constructor() {
super();
}
foo() {
super.prop = 2; // Cannot overwrite the value.
}
}
const y = new Y();
y.foo(); // TypeError: "prop" is read-only
console.log(y.prop); // 1
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Classes](/en-US/docs/Web/JavaScript/Reference/Classes)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/right_shift/index.md | ---
title: Right shift (>>)
slug: Web/JavaScript/Reference/Operators/Right_shift
page-type: javascript-operator
browser-compat: javascript.operators.right_shift
---
{{jsSidebar("Operators")}}
The **right shift (`>>`)** operator returns a number or BigInt 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 copies of the leftmost bit are shifted in from the left. This operation is also called "sign-propagating right shift" or "arithmetic right shift", because the sign of the resulting number is the same as the sign of the first operand.
{{EmbedInteractiveExample("pages/js/expressions-right-shift.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). 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 right shift 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 right shift. A {{jsxref("TypeError")}} is thrown if one operand becomes a BigInt but the other becomes a number.
Since the new leftmost bit has the same value as the previous leftmost bit, the sign bit (the leftmost bit) does not change. Hence the name "sign-propagating".
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`:
`9 >> 2` yields 2:
```plain
9 (base 10): 00000000000000000000000000001001 (base 2)
--------------------------------
9 >> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
```
Notice how two rightmost bits, `01`, have been shifted off, and two copies of the leftmost bit, `0` have been shifted in from the left.
`-9 >> 2` yields `-3`:
```plain
-9 (base 10): 11111111111111111111111111110111 (base 2)
--------------------------------
-9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)
```
Notice how two rightmost bits, `11`, have been shifted off. But as far as the leftmost bits: in this case, the leftmost bit is `1`. So two copies of that leftmost `1` bit have been shifted in from the left β which preserves the negative sign.
The binary representation `11111111111111111111111111111101` is equal to the negative decimal (base 10) number `-3`, because all negative integers are stored as [two's complements](https://en.wikipedia.org/wiki/Two's_complement), and this one can be calculated by inverting all the bits of the binary representation of the positive decimal (base 10) number `3`, which is `00000000000000000000000000000011`, and then adding one.
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.
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.
Right shifting any number `x` by `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 right shift
```js
9 >> 2; // 2
-9 >> 2; // -3
9n >> 2n; // 2n
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Bitwise operators in the JS guide](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#bitwise_operators)
- [Right shift assignment (`>>=`)](/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift_assignment)
- [Unsigned right shift (`>>>`)](/en-US/docs/Web/JavaScript/Reference/Operators/Unsigned_right_shift)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/exponentiation/index.md | ---
title: Exponentiation (**)
slug: Web/JavaScript/Reference/Operators/Exponentiation
page-type: javascript-operator
browser-compat: javascript.operators.exponentiation
---
{{jsSidebar("Operators")}}
The **exponentiation (`**`)** operator returns the result of raising the first operand to the power of the second operand. It is equivalent to {{jsxref("Math.pow()")}}, except it also accepts [BigInts](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) as operands.
{{EmbedInteractiveExample("pages/js/expressions-exponentiation.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 exponentiation if both operands become BigInts; otherwise, it performs number exponentiation. A {{jsxref("TypeError")}} is thrown if one operand becomes a BigInt but the other becomes a number.
For both numbers and BigInts, `0` raised to a positive power returns `0`, and `0` raised to a power of `0` returns `1`. For numbers, `0` raised to a negative number returns `Infinity`, while `-0` raised to a negative number returns `-Infinity`.
`NaN ** 0` (and the equivalent `Math.pow(NaN, 0)`) is the only case where {{jsxref("NaN")}} doesn't propagate through mathematical operations β it returns `1` despite the operand being `NaN`. In addition, the behavior where `base` is 1 and `exponent` is non-finite (Β±Infinity or `NaN`) is different from IEEE 754, which specifies that the result should be 1, whereas JavaScript returns `NaN` to preserve backward compatibility with its original behavior.
For BigInt exponentiation, a {{jsxref("RangeError")}} is thrown if the exponent `y` is negative. This is because any negative exponent would likely result in a value between 0 and 1 (unless the base is `1`, `-1`, or `0`), which is rounded to zero, and is likely a developer mistake.
The exponentiation operator is [right-associative](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence): `a ** b ** c` is equal to `a ** (b ** c)`.
In most languages, such as PHP, Python, and others that have an exponentiation operator (`**`), the exponentiation operator is defined to have a higher precedence than unary operators, such as unary `+` and unary `-`, but there are a few exceptions. For example, in Bash, the `**` operator is defined to have a lower precedence than unary operators.
In JavaScript, it is impossible to write an ambiguous exponentiation expression. That is, you cannot put a unary operator (with [precedence 14](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence#table), including `+`/`-`/`~`/`!`/`++`/`--`/`delete`/`void`/`typeof`/`await`) immediately before the base number; [doing so will cause a SyntaxError](/en-US/docs/Web/JavaScript/Reference/Errors/Unparenthesized_unary_expr_lhs_exponentiation).
For example, `-2 ** 2` is 4 in Bash, but is -4 in other languages (such as Python). This is invalid in JavaScript, as the operation is ambiguous. You have to parenthesize either side β for example, as `-(2 ** 2)` β to make the intention unambiguous.
Note that some programming languages use the caret symbol `^` for exponentiation, but JavaScript uses that symbol for the [bitwise XOR operator](/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_XOR).
## Examples
### Basic exponentiation
```js
2 ** 3; // 8
3 ** 2; // 9
3 ** 2.5; // 15.588457268119896
10 ** -1; // 0.1
2 ** 1024; // Infinity
NaN ** 2; // NaN
NaN ** 0; // 1
1 ** Infinity; // NaN
2n ** 3n; // 8n
2n ** 1024n; // A very large number, but not Infinity
2n ** 2; // TypeError: Cannot mix BigInt and other types, use explicit conversions
// To do exponentiation with a BigInt and a non-BigInt, convert either operand
2n ** BigInt(2); // 4n
Number(2n) ** 2; // 4
```
### Associativity
```js-nolint
2 ** 3 ** 2; // 512
2 ** (3 ** 2); // 512
(2 ** 3) ** 2; // 64
```
### Usage with unary operators
To invert the sign of the result of an exponentiation expression:
```js
-(2 ** 2); // -4
```
To force the base of an exponentiation expression to be a negative number:
```js
(-2) ** 2; // 4
```
## 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)
- [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)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/bitwise_xor_assignment/index.md | ---
title: Bitwise XOR assignment (^=)
slug: Web/JavaScript/Reference/Operators/Bitwise_XOR_assignment
page-type: javascript-operator
browser-compat: javascript.operators.bitwise_xor_assignment
---
{{jsSidebar("Operators")}}
The **bitwise XOR assignment (`^=`)** operator performs [bitwise XOR](/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_XOR) on the two operands and assigns the result to the left operand.
{{EmbedInteractiveExample("pages/js/expressions-bitwise-xor-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 XOR assignment
```js
let a = 5; // (00000000000000000000000000000101)
a ^= 3; // (00000000000000000000000000000011)
console.log(a); // 6 (00000000000000000000000000000110)
let b = 5; // (00000000000000000000000000000101)
b ^= 0; // (00000000000000000000000000000000)
console.log(b); // 5 (00000000000000000000000000000101)
let c = 5n;
c ^= 3n;
console.log(c); // 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)
- [Bitwise XOR (`^`)](/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_XOR)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/new.target/index.md | ---
title: new.target
slug: Web/JavaScript/Reference/Operators/new.target
page-type: javascript-language-feature
browser-compat: javascript.operators.new_target
---
{{jsSidebar("Operators")}}
The **`new.target`** meta-property lets you detect whether a function or constructor was called using the [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new) operator. In constructors and functions invoked using the [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new) operator, `new.target` returns a reference to the constructor or function that `new` was called upon. In normal function calls, `new.target` is {{jsxref("undefined")}}.
{{EmbedInteractiveExample("pages/js/expressions-newtarget.html")}}
## Syntax
```js-nolint
new.target
```
### Value
`new.target` is guaranteed to be a constructable function value or `undefined`.
- In class constructors, it refers to the class that `new` was called upon, which may be a subclass of the current constructor, because subclasses transitively call the superclass's constructor through [`super()`](/en-US/docs/Web/JavaScript/Reference/Operators/super).
- In ordinary functions, if the function is constructed directly with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new), `new.target` refers to the function itself. If the function is called without `new`, `new.target` is {{jsxref("undefined")}}. Functions can be used as the base class for [`extends`](/en-US/docs/Web/JavaScript/Reference/Classes/extends), in which case `new.target` may refer to the subclass.
- If a constructor (class or function) is called via {{jsxref("Reflect.construct()")}}, then `new.target` refers to the value passed as `newTarget` (which defaults to `target`).
- In [arrow functions](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), `new.target` is inherited from the surrounding scope. If the arrow function is not defined within another class or function which has a `new.target` {{Glossary("binding")}}, then a syntax error is thrown.
- In [static initialization blocks](/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks), `new.target` is {{jsxref("undefined")}}.
## Description
The `new.target` syntax consists of the keyword `new`, a dot, and the identifier `target`. Because `new` is a [reserved word](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#reserved_words), not an identifier, this is not a [property accessor](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors), but a special expression syntax.
The `new.target` meta-property is available in all function/class bodies; using `new.target` outside of functions or classes is a syntax error.
## Examples
### new\.target in function calls
In normal function calls (as opposed to constructor function calls), `new.target` is {{jsxref("undefined")}}. This lets you detect whether a function was called with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new) as a constructor.
```js
function Foo() {
if (!new.target) {
throw new Error("Foo() must be called with new");
}
console.log("Foo instantiated with new");
}
new Foo(); // Logs "Foo instantiated with new"
Foo(); // Throws "Foo() must be called with new"
```
### new\.target in constructors
In class constructors, `new.target` refers to the constructor that was directly invoked by `new`. This is also the case if the constructor is in a parent class and was delegated from a child constructor. `new.target` points to the class that `new` was called upon. For example, when `b` was initialized using `new B()`, the name of `B` was printed; and similarly, in case of `a`, the name of class `A` was printed.
```js
class A {
constructor() {
console.log(new.target.name);
}
}
class B extends A {
constructor() {
super();
}
}
const a = new A(); // Logs "A"
const b = new B(); // Logs "B"
```
### new\.target using Reflect.construct()
Before {{jsxref("Reflect.construct()")}} or classes, it was common to implement inheritance by passing the value of [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this), and letting the base constructor mutate it.
```js example-bad
function Base() {
this.name = "Base";
}
function Extended() {
// Only way to make the Base() constructor work on the existing
// `this` value instead of a new object that `new` creates.
Base.call(this);
this.otherProperty = "Extended";
}
Object.setPrototypeOf(Extended.prototype, Base.prototype);
Object.setPrototypeOf(Extended, Base);
console.log(new Extended()); // Extended { name: 'Base', otherProperty: 'Extended' }
```
However, {{jsxref("Function/call", "call()")}} and {{jsxref("Function/apply", "apply()")}} actually _call_ the function instead of _constructing_ it, so `new.target` has value `undefined`. This means that if `Base()` checks whether it's constructed with `new`, an error will be thrown, or it may behave in other unexpected ways. For example, you can't extend [`Map`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/Map) this way, because the `Map()` constructor cannot be called without `new`.
All built-in constructors directly construct the entire prototype chain of the new instance by reading `new.target.prototype`. So to make sure that (1) `Base` is constructed with `new`, and (2) `new.target` points to the subclass instead of `Base` itself, we need to use {{jsxref("Reflect.construct()")}}.
```js
function BetterMap(entries) {
// Call the base class constructor, but setting `new.target` to the subclass,
// so that the instance created has the correct prototype chain.
return Reflect.construct(Map, [entries], BetterMap);
}
BetterMap.prototype.upsert = function (key, actions) {
if (this.has(key)) {
this.set(key, actions.update(this.get(key)));
} else {
this.set(key, actions.insert());
}
};
Object.setPrototypeOf(BetterMap.prototype, Map.prototype);
Object.setPrototypeOf(BetterMap, Map);
const map = new BetterMap([["a", 1]]);
map.upsert("a", {
update: (value) => value + 1,
insert: () => 1,
});
console.log(map.get("a")); // 2
```
> **Note:** In fact, due to the lack of `Reflect.construct()`, it is not possible to properly subclass built-ins (like [`Error` subclassing](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#custom_error_types)) when transpiling to pre-ES6 code.
However, if you are writing ES6 code, prefer using classes and `extends` instead, as it's more readable and less error-prone.
```js
class BetterMap extends Map {
// The constructor is omitted because it's just the default one
upsert(key, actions) {
if (this.has(key)) {
this.set(key, actions.update(this.get(key)));
} else {
this.set(key, actions.insert());
}
}
}
const map = new BetterMap([["a", 1]]);
map.upsert("a", {
update: (value) => value + 1,
insert: () => 1,
});
console.log(map.get("a")); // 2
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Functions](/en-US/docs/Web/JavaScript/Reference/Functions)
- [Classes](/en-US/docs/Web/JavaScript/Reference/Classes)
- [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new)
- [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/function_star_/index.md | ---
title: function* expression
slug: Web/JavaScript/Reference/Operators/function*
page-type: javascript-operator
browser-compat: javascript.operators.generator_function
---
{{jsSidebar("Operators")}}
The **`function*`** keyword can be used to define a generator function inside an expression.
You can also define generator functions using the [`function*` declaration](/en-US/docs/Web/JavaScript/Reference/Statements/function*).
{{EmbedInteractiveExample("pages/js/expressions-functionasteriskexpression.html", "taller")}}
## 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, allowing you to create an ad-hoc [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol). See also the chapter about [functions](/en-US/docs/Web/JavaScript/Reference/Functions) for more information.
## Examples
### Using function\* expression
The following example defines an unnamed generator function and assigns it to `x`. The function yields the square of its argument:
```js
const x = function* (y) {
yield y * y;
};
```
## 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("GeneratorFunction")}}
- [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
- {{jsxref("Operators/yield", "yield")}}
- {{jsxref("Operators/yield*", "yield*")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/bitwise_xor/index.md | ---
title: Bitwise XOR (^)
slug: Web/JavaScript/Reference/Operators/Bitwise_XOR
page-type: javascript-operator
browser-compat: javascript.operators.bitwise_xor
---
{{jsSidebar("Operators")}}
The **bitwise XOR (`^`)** operator returns a number or BigInt whose binary representation has a `1` in each bit position for which the corresponding bits of either but not both operands are `1`.
{{EmbedInteractiveExample("pages/js/expressions-bitwise-xor.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 XOR 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 XOR. 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 XOR operation is:
| x | y | x XOR y |
| --- | --- | ------- |
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
```plain
9 (base 10) = 00000000000000000000000000001001 (base 2)
14 (base 10) = 00000000000000000000000000001110 (base 2)
--------------------------------
14 ^ 9 (base 10) = 00000000000000000000000000000111 (base 2) = 7 (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 XORing 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 XOR
```js
// 9 (00000000000000000000000000001001)
// 14 (00000000000000000000000000001110)
14 ^ 9;
// 7 (00000000000000000000000000000111)
14n ^ 9n; // 7n
```
## 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 XOR assignment (`^=`)](/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_XOR_assignment)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/greater_than_or_equal/index.md | ---
title: Greater than or equal (>=)
slug: Web/JavaScript/Reference/Operators/Greater_than_or_equal
page-type: javascript-operator
browser-compat: javascript.operators.greater_than_or_equal
---
{{jsSidebar("Operators")}}
The **greater than or equal (`>=`)** operator returns `true` if
the left operand is greater than or equal to the right operand, and `false`
otherwise.
{{EmbedInteractiveExample("pages/js/expressions-greater-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 result negated. `x >= y` is generally equivalent to `!(x < y)`, 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`.)
`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"; // false
"a" >= "a"; // true
"a" >= "3"; // true
```
### String to number comparison
```js
"5" >= 3; // true
"3" >= 3; // true
"3" >= 5; // false
"hello" >= 5; // false
5 >= "hello"; // false
```
### Number to Number comparison
```js
5 >= 3; // true
3 >= 3; // true
3 >= 5; // false
```
### Number to BigInt comparison
```js
5n >= 3; // true
3 >= 3n; // true
3 >= 5n; // false
```
### Comparing Boolean, null, undefined, NaN
```js
true >= false; // true
true >= true; // true
false >= true; // false
true >= 0; // true
true >= 1; // true
null >= 0; // true
1 >= null; // true
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)
- [Less than (`<`)](/en-US/docs/Web/JavaScript/Reference/Operators/Less_than)
- [Less than or equal (`<=`)](/en-US/docs/Web/JavaScript/Reference/Operators/Less_than_or_equal)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/addition_assignment/index.md | ---
title: Addition assignment (+=)
slug: Web/JavaScript/Reference/Operators/Addition_assignment
page-type: javascript-operator
browser-compat: javascript.operators.addition_assignment
---
{{jsSidebar("Operators")}}
The **addition assignment (`+=`)** operator performs [addition](/en-US/docs/Web/JavaScript/Reference/Operators/Addition) (which is either numeric addition or string concatenation) on the two operands and assigns the result to the left operand.
{{EmbedInteractiveExample("pages/js/expressions-addition-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 addition assignment
```js
let baz = true;
// Boolean + Number -> addition
baz += 1; // 2
// Number + Boolean -> addition
baz += false; // 2
```
```js
let foo = "foo";
// String + Boolean -> concatenation
foo += false; // "foofalse"
// String + String -> concatenation
foo += "bar"; // "foofalsebar"
```
```js
let bar = 5;
// Number + Number -> addition
bar += 2; // 7
// Number + String -> concatenation
bar += "foo"; // "7foo"
```
```js
let x = 1n;
// BigInt + BigInt -> addition
x += 2n; // 3n
// BigInt + Number -> throws TypeError
x += 1; // TypeError: Cannot mix BigInt and other types, use explicit conversions
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Assignment operators in the JS guide](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#assignment_operators)
- [Addition (`+`)](/en-US/docs/Web/JavaScript/Reference/Operators/Addition)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/bitwise_and/index.md | ---
title: Bitwise AND (&)
slug: Web/JavaScript/Reference/Operators/Bitwise_AND
page-type: javascript-operator
browser-compat: javascript.operators.bitwise_and
---
{{jsSidebar("Operators")}}
The **bitwise AND (`&`)** operator returns a number or BigInt whose binary representation has a `1` in each bit position for which the corresponding bits of both operands are `1`.
{{EmbedInteractiveExample("pages/js/expressions-bitwise-and.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 AND 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 AND. 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 AND operation is:
| x | y | x AND y |
| --- | --- | ------- |
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |
```plain
9 (base 10) = 00000000000000000000000000001001 (base 2)
14 (base 10) = 00000000000000000000000000001110 (base 2)
--------------------------------
14 & 9 (base 10) = 00000000000000000000000000001000 (base 2) = 8 (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 ANDing any number `x` with `-1` returns `x` converted to a 32-bit integer. Do not use `& -1` 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 AND
```js
// 9 (00000000000000000000000000001001)
// 14 (00000000000000000000000000001110)
14 & 9;
// 8 (00000000000000000000000000001000)
14n & 9n; // 8n
```
## 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 AND assignment (`&=`)](/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND_assignment)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/addition/index.md | ---
title: Addition (+)
slug: Web/JavaScript/Reference/Operators/Addition
page-type: javascript-operator
browser-compat: javascript.operators.addition
---
{{jsSidebar("Operators")}}
The **addition (`+`)** operator produces the sum of numeric operands or string concatenation.
{{EmbedInteractiveExample("pages/js/expressions-addition.html")}}
## Syntax
```js-nolint
x + y
```
## Description
The `+` operator is overloaded for two distinct operations: numeric addition and string concatenation. When evaluating, it first [coerces both operands to primitives](/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion). Then, the two operands' types are tested:
- If one side is a string, the other operand is also [converted to a string](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) and they are concatenated.
- If they are both [BigInts](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt), BigInt addition is performed. If one side is a BigInt but the other is not, a {{jsxref("TypeError")}} is thrown.
- Otherwise, both sides are [converted to numbers](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion), and numeric addition is performed.
String concatenation is often thought to be equivalent with [template literals](/en-US/docs/Web/JavaScript/Reference/Template_literals) or [`String.prototype.concat()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/concat), but they are not. Addition coerces the expression to a _primitive_, which calls [`valueOf()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf) in priority; on the other hand, template literals and `concat()` coerce the expression to a _string_, which calls [`toString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString) in priority. If the expression has a [`@@toPrimitive`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive) method, string concatenation calls it with `"default"` as hint, while template literals use `"string"`. This is important for objects that have different string and primitive representations β such as [Temporal](https://github.com/tc39/proposal-temporal), whose `valueOf()` method throws.
```js
const t = Temporal.Now.instant();
"" + t; // Throws TypeError
`${t}`; // '2022-07-31T04:48:56.113918308Z'
"".concat(t); // '2022-07-31T04:48:56.113918308Z'
```
You are advised to not use `"" + x` to perform [string coercion](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion).
## Examples
### Number addition
```js
// Number + Number -> addition
1 + 2; // 3
// Boolean + Number -> addition
true + 1; // 2
// Boolean + Boolean -> addition
false + false; // 0
```
### BigInt addition
```js
// BigInt + BigInt -> addition
1n + 2n; // 3n
// BigInt + Number -> throws TypeError
1n + 2; // TypeError: Cannot mix BigInt and other types, use explicit conversions
// To add a BigInt to a non-BigInt, convert either operand
1n + BigInt(2); // 3n
Number(1n) + 2; // 3
```
### String concatenation
```js
// String + String -> concatenation
"foo" + "bar"; // "foobar"
// Number + String -> concatenation
5 + "foo"; // "5foo"
// String + Boolean -> concatenation
"foo" + false; // "foofalse"
// String + Number -> concatenation
"2" + 2; // "22"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [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)
- [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)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/void/index.md | ---
title: void operator
slug: Web/JavaScript/Reference/Operators/void
page-type: javascript-operator
browser-compat: javascript.operators.void
---
{{jsSidebar("Operators")}}
The **`void`** operator evaluates the given
`expression` and then returns {{jsxref("undefined")}}.
{{EmbedInteractiveExample("pages/js/expressions-voidoperator.html", "taller")}}
## Syntax
```js-nolint
void expression
```
## Description
This operator allows evaluating expressions that produce a value into places where an
expression that evaluates to {{jsxref("undefined")}} is desired.
The `void` operator is often used merely to obtain the
`undefined` primitive value, usually using `void(0)` (which is
equivalent to `void 0`). In these cases, the global variable
{{jsxref("undefined")}} can be used.
It should be noted that [the precedence](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence)
of the `void` operator should be taken into account and that
parentheses can help clarify the resolution of the expression following the
`void` operator:
```js
void 2 === "2"; // (void 2) === '2', returns false
void (2 === "2"); // void (2 === '2'), returns undefined
```
## Examples
### Immediately Invoked Function Expressions
When using an [immediately-invoked function expression](/en-US/docs/Glossary/IIFE), the `function` keyword cannot be at the immediate start of the [statement](/en-US/docs/Web/JavaScript/Reference/Statements/Expression_statement), because that would be parsed as a [function declaration](/en-US/docs/Web/JavaScript/Reference/Statements/function), and would generate a syntax error when the parentheses representing invocation is reached β if the function is unnamed, it would immediately be a syntax error if the function is parsed as a declaration.
```js-nolint example-bad
function iife() {
console.log("Executed!");
}(); // SyntaxError: Unexpected token ')'
function () {
console.log("Executed!");
}(); // SyntaxError: Function statements require a function name
```
In order for the function to be parsed as an [expression](/en-US/docs/Web/JavaScript/Reference/Operators/function), the `function` keyword has to appear at a position that only accepts expressions, not statements. This can be achieved be prefixing the keyword with a [unary operator](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#unary_operators), which only accepts expressions as operands. Function invocation has higher [precedence](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence) than unary operators, so it will be executed first. Its return value (which is almost always `undefined`) will be passed to the unary operator and then immediately discarded.
Of all the unary operators, `void` offers the best semantic, because it clearly signals that the return value of the function invocation should be discarded.
```js-nolint
void function () {
console.log("Executed!");
}();
// Logs "Executed!"
```
This is a bit longer than wrapping the function expression in parentheses, which has the same effect of forcing the `function` keyword to be parsed as the start of an expression instead of a statement.
```js
(function () {
console.log("Executed!");
})();
```
### JavaScript URIs
When a browser follows a `javascript:` URI, it evaluates the code in the URI
and then replaces the contents of the page with the returned value, unless the returned
value is {{jsxref("undefined")}}. The `void` operator can be used to return
`undefined`. For example:
```html
<a href="javascript:void(0);">Click here to do nothing</a>
<a href="javascript:void(document.body.style.backgroundColor='green');">
Click here for green background
</a>
```
> **Note:** `javascript:` pseudo protocol is discouraged over
> other alternatives, such as unobtrusive event handlers.
### Non-leaking Arrow Functions
Arrow functions introduce a short-hand braceless syntax that returns an expression.
This can cause unintended side effects if the expression is a function call where the returned value changes from `undefined` to some other value.
For example, if `doSomething()` returns `false` in the code below, the checkbox will no longer be marked as checked or unchecked when the checkbox is clicked (setting the handler to `false` disables the default action).
```js example-bad
checkbox.onclick = () => doSomething();
```
This is unlikely to be desired behaviour!
To be safe, when the return value of a function is not intended to be used, it can be passed to the `void` operator to ensure that (for example) changing APIs do not cause arrow functions' behaviors to change.
```js example-good
checkbox.onclick = () => void doSomething();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("undefined")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/bitwise_not/index.md | ---
title: Bitwise NOT (~)
slug: Web/JavaScript/Reference/Operators/Bitwise_NOT
page-type: javascript-operator
browser-compat: javascript.operators.bitwise_not
---
{{jsSidebar("Operators")}}
The **bitwise NOT (`~`)** operator returns a number or BigInt whose binary representation has a `1` in each bit position for which the corresponding bit of the operand is `0`, and a `0` otherwise.
{{EmbedInteractiveExample("pages/js/expressions-bitwise-not.html")}}
## Syntax
```js-nolint
~x
```
## 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 the operand to a numeric value](/en-US/docs/Web/JavaScript/Data_structures#numeric_coercion) and tests the type of it. It performs BigInt NOT if the operand becomes a BigInt; otherwise, it converts the operand to a [32-bit integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#fixed-width_number_conversion) and performs number bitwise NOT.
The operator operates on the operands' bit representations in [two's complement](https://en.wikipedia.org/wiki/Two's_complement). The operator is applied to each bit, and the result is constructed bitwise.
The truth table for the NOT operation is:
| x | NOT x |
| --- | ----- |
| 0 | 1 |
| 1 | 0 |
```plain
9 (base 10) = 00000000000000000000000000001001 (base 2)
--------------------------------
~9 (base 10) = 11111111111111111111111111110110 (base 2) = -10 (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 NOTing any 32-bit integer `x` yields `-(x + 1)`. For example, `~-5` yields `4`.
Bitwise NOTing any number `x` twice returns `x` converted to a 32-bit integer. Do not use `~~x` 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. Due to using 32-bit representation for numbers, both `~-1` and `~4294967295` (2<sup>32</sup> - 1) result in `0`.
## Examples
### Using bitwise NOT
```js
~0; // -1
~-1; // 0
~1; // -2
~0n; // -1n
~4294967295n; // -4294967296n
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Bitwise operators in the JS guide](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#bitwise_operators)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/await/index.md | ---
title: await
slug: Web/JavaScript/Reference/Operators/await
page-type: javascript-operator
browser-compat: javascript.operators.await
---
{{jsSidebar("Operators")}}
The **`await`** operator is used to wait for a {{jsxref("Promise")}} and get its fulfillment value. It can only be used inside an [async function](/en-US/docs/Web/JavaScript/Reference/Statements/async_function) or at the top level of a [module](/en-US/docs/Web/JavaScript/Guide/Modules).
## Syntax
```js-nolint
await expression
```
### Parameters
- `expression`
- : A {{jsxref("Promise")}}, a [thenable object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables), or any value to wait for.
### Return value
The fulfillment value of the promise or thenable object, or, if the expression is not thenable, the expression's own value.
### Exceptions
Throws the rejection reason if the promise or thenable object is rejected.
## Description
`await` is usually used to unwrap promises by passing a {{jsxref("Promise")}} as the `expression`. Using `await` pauses the execution of its surrounding `async` function until the promise is settled (that is, fulfilled or rejected). When execution resumes, the value of the `await` expression becomes that of the fulfilled promise.
If the promise is rejected, the `await` expression throws the rejected value. The function containing the `await` expression will [appear in the stack trace](#improving_stack_trace) of the error. Otherwise, if the rejected promise is not awaited or is immediately returned, the caller function will not appear in the stack trace.
The `expression` is resolved in the same way as {{jsxref("Promise.resolve()")}}: it's always converted to a native `Promise` and then awaited. If the `expression` is a:
- Native `Promise` (which means `expression` belongs to `Promise` or a subclass, and `expression.constructor === Promise`): The promise is directly used and awaited natively, without calling `then()`.
- [Thenable object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) (including non-native promises, polyfill, proxy, child class, etc.): A new promise is constructed with the native [`Promise()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise) constructor by calling the object's `then()` method and passing in a handler that calls the `resolve` callback.
- Non-thenable value: An already-fulfilled `Promise` is constructed and used.
Even when the used promise is already fulfilled, the async function's execution still pauses until the next tick. In the meantime, the caller of the async function resumes execution. [See example below.](#control_flow_effects_of_await)
Because `await` is only valid inside async functions and modules, which themselves are asynchronous and return promises, the `await` expression never blocks the main thread and only defers execution of code that actually depends on the result, i.e. anything after the `await` expression.
## Examples
### Awaiting a promise to be fulfilled
If a `Promise` is passed to an `await` expression, it waits for the `Promise` to be fulfilled and returns the fulfilled value.
```js
function resolveAfter2Seconds(x) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function f1() {
const x = await resolveAfter2Seconds(10);
console.log(x); // 10
}
f1();
```
### Thenable objects
[Thenable objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) are resolved just the same as actual `Promise` objects.
```js
async function f() {
const thenable = {
then(resolve, _reject) {
resolve("resolved!");
},
};
console.log(await thenable); // "resolved!"
}
f();
```
They can also be rejected:
```js
async function f() {
const thenable = {
then(resolve, reject) {
reject(new Error("rejected!"));
},
};
await thenable; // Throws Error: rejected!
}
f();
```
### Conversion to promise
If the value is not a `Promise`, `await` converts the value to a resolved `Promise`, and waits for it. The awaited value's identity doesn't change as long as it doesn't have a `then` property that's callable.
```js
async function f3() {
const y = await 20;
console.log(y); // 20
const obj = {};
console.log((await obj) === obj); // true
}
f3();
```
### Handling rejected promises
If the `Promise` is rejected, the rejected value is thrown.
```js
async function f4() {
try {
const z = await Promise.reject(30);
} catch (e) {
console.error(e); // 30
}
}
f4();
```
You can handle rejected promises without a `try` block by chaining a [`catch()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch) handler before awaiting the promise.
```js
const response = await promisedFunction().catch((err) => {
console.error(err);
return "default response";
});
// response will be "default response" if the promise is rejected
```
This is built on the assumption that `promisedFunction()` never synchronously throws an error, but always returns a rejected promise. This is the case for most properly-designed promise-based functions, which usually look like:
```js
function promisedFunction() {
// Immediately return a promise to minimize chance of an error being thrown
return new Promise((resolve, reject) => {
// do something async
});
}
```
However, if `promisedFunction()` does throw an error synchronously, the error won't be caught by the `catch()` handler. In this case, the `try...catch` statement is necessary.
### Top level await
You can use the `await` keyword on its own (outside of an async function) at the top level of a [module](/en-US/docs/Web/JavaScript/Guide/Modules). This means that modules with child modules that use `await` will wait for the child modules to execute before they themselves run, all while not blocking other child modules from loading.
Here is an example of a simple module using the [Fetch API](/en-US/docs/Web/API/Fetch_API) and specifying await within the [`export`](/en-US/docs/Web/JavaScript/Reference/Statements/export) statement. Any modules that include this will wait for the fetch to resolve before running any code.
```js
// fetch request
const colors = fetch("../data/colors.json").then((response) => response.json());
export default await colors;
```
### Control flow effects of await
When an `await` is encountered in code (either in an async function or in a module), the awaited expression is executed, while all code that depends on the expression's value is paused and pushed into the [microtask queue](/en-US/docs/Web/JavaScript/Event_loop). The main thread is then freed for the next task in the event loop. This happens even if the awaited value is an already-resolved promise or not a promise. For example, consider the following code:
```js
async function foo(name) {
console.log(name, "start");
console.log(name, "middle");
console.log(name, "end");
}
foo("First");
foo("Second");
// First start
// First middle
// First end
// Second start
// Second middle
// Second end
```
In this case, the two async functions are synchronous in effect, because they don't contain any `await` expression. The three statements happen in the same tick. In promise terms, the function corresponds to:
```js
function foo(name) {
return new Promise((resolve) => {
console.log(name, "start");
console.log(name, "middle");
console.log(name, "end");
resolve();
});
}
```
However, as soon as there's one `await`, the function becomes asynchronous, and execution of following statements is deferred to the next tick.
```js
async function foo(name) {
console.log(name, "start");
await console.log(name, "middle");
console.log(name, "end");
}
foo("First");
foo("Second");
// First start
// First middle
// Second start
// Second middle
// First end
// Second end
```
This corresponds to:
```js
function foo(name) {
return new Promise((resolve) => {
console.log(name, "start");
resolve(console.log(name, "middle"));
}).then(() => {
console.log(name, "end");
});
}
```
While the extra `then()` handler is not necessary, and the handler can be merged with the executor passed to the constructor, the `then()` handler's existence means the code will take one extra tick to complete. The same happens for `await`. Therefore, make sure to use `await` only when necessary (to unwrap promises into their values).
Other microtasks can execute before the async function resumes. This example uses [`queueMicrotask()`](/en-US/docs/Web/API/queueMicrotask) to demonstrate how the microtask queue is processed when each `await` expression is encountered.
```js
let i = 0;
queueMicrotask(function test() {
i++;
console.log("microtask", i);
if (i < 3) {
queueMicrotask(test);
}
});
(async () => {
console.log("async function start");
for (let i = 1; i < 3; i++) {
await null;
console.log("async function resume", i);
}
await null;
console.log("async function end");
})();
queueMicrotask(() => {
console.log("queueMicrotask() after calling async function");
});
console.log("script sync part end");
// Logs:
// async function start
// script sync part end
// microtask 1
// async function resume 1
// queueMicrotask() after calling async function
// microtask 2
// async function resume 2
// microtask 3
// async function end
```
In this example, the `test()` function is always called before the async function resumes, so the microtasks they each schedule are always executed in an intertwined fashion. On the other hand, because both `await` and `queueMicrotask()` schedule microtasks, the order of execution is always based on the order of scheduling. This is why the "queueMicrotask() after calling async function" log happens after the async function resumes for the first time.
### Improving stack trace
Sometimes, the `await` is omitted when a promise is directly returned from an async function.
```js
async function noAwait() {
// Some actions...
return /* await */ lastAsyncTask();
}
```
However, consider the case where `lastAsyncTask` asynchronously throws an error.
```js
async function lastAsyncTask() {
await null;
throw new Error("failed");
}
async function noAwait() {
return lastAsyncTask();
}
noAwait();
// Error: failed
// at lastAsyncTask
```
Only `lastAsyncTask` appears in the stack trace, because the promise is rejected after it has already been returned from `noAwait` β in some sense, the promise is unrelated to `noAwait`. To improve the stack trace, you can use `await` to unwrap the promise, so that the exception gets thrown into the current function. The exception will then be immediately wrapped into a new rejected promise, but during error creation, the caller will appear in the stack trace.
```js
async function lastAsyncTask() {
await null;
throw new Error("failed");
}
async function withAwait() {
return await lastAsyncTask();
}
withAwait();
// Error: failed
// at lastAsyncTask
// at async withAwait
```
However, there's a little performance penalty coming with `return await` because the promise has to be unwrapped and wrapped again.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Statements/async_function", "async function")}}
- [`async function` expression](/en-US/docs/Web/JavaScript/Reference/Operators/async_function)
- {{jsxref("AsyncFunction")}}
- [Top-level await](https://v8.dev/features/top-level-await) on v8.dev (2019)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/unary_plus/index.md | ---
title: Unary plus (+)
slug: Web/JavaScript/Reference/Operators/Unary_plus
page-type: javascript-operator
browser-compat: javascript.operators.unary_plus
---
{{jsSidebar("Operators")}}
The **unary plus (`+`)** operator precedes its operand and evaluates to its
operand but attempts to [convert it into a number](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion), if it isn't already.
{{EmbedInteractiveExample("pages/js/expressions-unary-plus.html", "taller")}}
## Syntax
```js-nolint
+x
```
## Description
Although unary negation (`-`) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number.
Unary plus does the exact same steps as normal [number coercion](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion) used by most built-in methods expecting numbers. It can convert string representations of integers and floats, as well as the non-string values `true`, `false`, and `null`. Integers in both decimal and hexadecimal (`0x`-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to {{jsxref("NaN")}}. Unlike other arithmetic operators, which work with both numbers and [BigInts](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt), using the `+` operator on BigInt values throws a {{jsxref("TypeError")}}.
## Examples
### Usage with numbers
```js
const x = 1;
const y = -1;
console.log(+x);
// 1
console.log(+y);
// -1
```
### Usage with non-numbers
```js-nolint
+true // 1
+false // 0
+null // 0
+[] // 0
+function (val) { return val; } // NaN
+1n // throws TypeError: Cannot convert BigInt value to number
```
## 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)
- [Decrement (`--`)](/en-US/docs/Web/JavaScript/Reference/Operators/Decrement)
- [Unary negation (`-`)](/en-US/docs/Web/JavaScript/Reference/Operators/Unary_negation)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/remainder_assignment/index.md | ---
title: Remainder assignment (%=)
slug: Web/JavaScript/Reference/Operators/Remainder_assignment
page-type: javascript-operator
browser-compat: javascript.operators.remainder_assignment
---
{{jsSidebar("Operators")}}
The **remainder assignment (`%=`)** operator performs [remainder](/en-US/docs/Web/JavaScript/Reference/Operators/Remainder) on the two operands and assigns the result to the left operand.
{{EmbedInteractiveExample("pages/js/expressions-remainder-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 remainder assignment
```js
let bar = 5;
bar %= 2; // 1
bar %= "foo"; // NaN
bar %= 0; // NaN
let foo = 3n;
foo %= 2n; // 1n
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Assignment operators in the JS guide](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#assignment_operators)
- [Remainder (`%`)](/en-US/docs/Web/JavaScript/Reference/Operators/Remainder)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/delete/index.md | ---
title: delete
slug: Web/JavaScript/Reference/Operators/delete
page-type: javascript-operator
browser-compat: javascript.operators.delete
---
{{jsSidebar("Operators")}}
The **`delete`** operator removes a property from an object. If the property's value is an object and there are no more references to the object, the object held by that property is eventually released automatically.
{{EmbedInteractiveExample("pages/js/expressions-deleteoperator.html")}}
## Syntax
```js-nolint
delete object.property
delete object[property]
```
> **Note:** The syntax allows a wider range of expressions following the `delete` operator, but only the above forms lead to meaningful behaviors.
### Parameters
- `object`
- : The name of an object, or an expression evaluating to an object.
- `property`
- : The property to delete.
### Return value
`true` for all cases except when the property is an [own](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn) [non-configurable](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#configurable_attribute) property, in which case `false` is returned in non-strict mode.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode) if the property is an own non-configurable property.
- {{jsxref("ReferenceError")}}
- : Thrown if `object` is [`super`](/en-US/docs/Web/JavaScript/Reference/Operators/super).
## Description
The `delete` operator has the same [precedence](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence) as other unary operators like [`typeof`](/en-US/docs/Web/JavaScript/Reference/Operators/typeof). Therefore, it accepts any expression formed by higher-precedence operators. However, the following forms lead to early syntax errors in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode):
```js-nolint example-bad
delete identifier;
delete object.#privateProperty;
```
Because [classes](/en-US/docs/Web/JavaScript/Reference/Classes) are automatically in strict mode, and [private properties](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties) can only be legally referenced in class bodies, this means private properties can never be deleted. While `delete identifier` [may work](#deleting_global_properties) if `identifier` refers to a configurable property of the global object, you should avoid this form and prefix it with [`globalThis`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis) instead.
While other expressions are accepted, they don't lead to meaningful behaviors:
```js example-bad
delete console.log(1);
// Logs 1, returns true, but nothing deleted
```
The `delete` operator removes a given property from an object. On successful deletion, it will return `true`, else `false` will be returned. Unlike what common belief suggests (perhaps due to other programming languages like [delete in C++](https://docs.microsoft.com/cpp/cpp/delete-operator-cpp?view=msvc-170)), the `delete` operator has **nothing** to do with directly freeing memory. Memory management is done indirectly via breaking references. See the [memory management](/en-US/docs/Web/JavaScript/Memory_management) page for more details.
It is important to consider the following scenarios:
- If the property which you are trying to delete does not exist, `delete` will not have any effect and will return `true`.
- `delete` only has an effect on own properties. If a property with the same name exists on the object's prototype chain, then after deletion, the object will use the property from the prototype chain.
- Non-configurable properties cannot be removed. This includes properties of built-in objects like {{jsxref("Math")}}, {{jsxref("Array")}}, {{jsxref("Object")}} and properties that are created as non-configurable with methods like {{jsxref("Object.defineProperty()")}}.
- Deleting variables, including function parameters, never works. `delete variable` will throw a {{jsxref("SyntaxError")}} in strict mode, and will have no effect in non-strict mode.
- Any variable declared with {{jsxref("Statements/var", "var")}} cannot be deleted from the global scope or from a function's scope, because while they may be attached to the [global object](/en-US/docs/Glossary/Global_object), they are not configurable.
- Any variable declared with {{jsxref("Statements/let", "let")}} or {{jsxref("Statements/const", "const")}} cannot be deleted from the scope within which they were defined, because they are not attached to an object.
## Examples
### Using delete
> **Note:** The following example uses non-strict-mode only features, like implicitly creating global variables and deleting identifiers, which are forbidden in strict mode.
```js
// Creates the property empCount on the global scope.
// Since we are using var, this is marked as non-configurable.
var empCount = 43;
// Creates the property EmployeeDetails on the global scope.
// Since it was defined without "var", it is marked configurable.
EmployeeDetails = {
name: "xyz",
age: 5,
designation: "Developer",
};
// delete can be used to remove properties from objects.
delete EmployeeDetails.name; // returns true
// Even when the property does not exist, delete returns "true".
delete EmployeeDetails.salary; // returns true
// EmployeeDetails is a property of the global scope.
delete EmployeeDetails; // returns true
// On the contrary, empCount is not configurable
// since var was used.
delete empCount; // returns false
// delete also does not affect built-in static properties
// that are non-configurable.
delete Math.PI; // returns false
function f() {
var z = 44;
// delete doesn't affect local variable names
delete z; // returns false
}
```
### delete and the prototype chain
In the following example, we delete an own property of an object while a property with the same name is available on the prototype chain:
```js
function Foo() {
this.bar = 10;
}
Foo.prototype.bar = 42;
const foo = new Foo();
// foo.bar is associated with the
// own property.
console.log(foo.bar); // 10
// Delete the own property within the
// foo object.
delete foo.bar; // returns true
// foo.bar is still available in the
// prototype chain.
console.log(foo.bar); // 42
// Delete the property on the prototype.
delete Foo.prototype.bar; // returns true
// The "bar" property can no longer be
// inherited from Foo since it has been
// deleted.
console.log(foo.bar); // undefined
```
### Deleting array elements
When you delete an array element, the array `length` is not affected. This holds even if you delete the last element of the array.
When the `delete` operator removes an array element, that element is no longer in the array. In the following example, `trees[3]` is removed with `delete`.
```js
const trees = ["redwood", "bay", "cedar", "oak", "maple"];
delete trees[3];
console.log(3 in trees); // false
```
This creates a [sparse array](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays) with an empty slot. If you want an array element to exist but have an undefined value, use the `undefined` value instead of the `delete` operator. In the following example, `trees[3]` is assigned the value `undefined`, but the array element still exists:
```js
const trees = ["redwood", "bay", "cedar", "oak", "maple"];
trees[3] = undefined;
console.log(3 in trees); // true
```
If instead, you want to remove an array element by changing the contents of the array, use the {{jsxref("Array/splice", "splice()")}} method. In the following example, `trees[3]` is removed from the array completely using {{jsxref("Array/splice", "splice()")}}:
```js
const trees = ["redwood", "bay", "cedar", "oak", "maple"];
trees.splice(3, 1);
console.log(trees); // ["redwood", "bay", "cedar", "maple"]
```
### Deleting non-configurable properties
When a property is marked as non-configurable, `delete` won't have any effect, and will return `false`. In strict mode, this will raise a `TypeError`.
```js
const Employee = {};
Object.defineProperty(Employee, "name", { configurable: false });
console.log(delete Employee.name); // returns false
```
{{jsxref("Statements/var", "var")}} creates non-configurable properties that cannot be deleted with the `delete` operator:
```js
// Since "nameOther" is added using with the
// var keyword, it is marked as non-configurable
var nameOther = "XYZ";
// We can access this global property using:
Object.getOwnPropertyDescriptor(globalThis, "nameOther");
// {
// value: "XYZ",
// writable: true,
// enumerable: true,
// configurable: false
// }
delete globalThis.nameOther; // return false
```
In strict mode, this would raise an exception.
### Deleting global properties
If a global property is configurable (for example, via direct property assignment), it can be deleted, and subsequent references to them as global variables will produce a {{jsxref("ReferenceError")}}.
```js
globalThis.globalVar = 1;
console.log(globalVar); // 1
// In non-strict mode, you can use `delete globalVar` as well
delete globalThis.globalVar;
console.log(globalVar); // ReferenceError: globalVar is not defined
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [In depth analysis on delete](http://perfectionkills.com/understanding-delete/)
- {{jsxref("Reflect.deleteProperty()")}}
- {{jsxref("Map.prototype.delete()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/left_shift/index.md | ---
title: Left shift (<<)
slug: Web/JavaScript/Reference/Operators/Left_shift
page-type: javascript-operator
browser-compat: javascript.operators.left_shift
---
{{jsSidebar("Operators")}}
The **left shift (`<<`)** operator returns a number or BigInt whose binary representation is the first operand shifted by the specified number of bits to the left. Excess bits shifted off to the left are discarded, and zero bits are shifted in from the right.
{{EmbedInteractiveExample("pages/js/expressions-left-shift.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 left shift 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 left shift. A {{jsxref("TypeError")}} is thrown if one operand becomes a BigInt but the other becomes a number.
The operator operates on the left operand's bit representation in [two's complement](https://en.wikipedia.org/wiki/Two's_complement). For example, `9 << 2` yields 36:
```plain
9 (base 10): 00000000000000000000000000001001 (base 2)
--------------------------------
9 << 2 (base 10): 00000000000000000000000000100100 (base 2) = 36 (base 10)
```
Bitwise a 32-bit integer `x` to the left by `y` bits yields `x * 2 ** y`. So for example, `9 << 3` is equivalent to `9 * (2 ** 3) = 9 * (8) = 72`.
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.
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.
Left shifting any number `x` by `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 left shift
```js
9 << 3; // 72
// 9 * (2 ** 3) = 9 * (8) = 72
9n << 3n; // 72n
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Bitwise operators in the JS guide](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#bitwise_operators)
- [Left shift assignment (`<<=`)](/en-US/docs/Web/JavaScript/Reference/Operators/Left_shift_assignment)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/strict_equality/index.md | ---
title: Strict equality (===)
slug: Web/JavaScript/Reference/Operators/Strict_equality
page-type: javascript-operator
browser-compat: javascript.operators.strict_equality
---
{{jsSidebar("Operators")}}
The **strict equality (`===`)** operator checks whether its two operands are
equal, returning a Boolean result. Unlike the [equality](/en-US/docs/Web/JavaScript/Reference/Operators/Equality) operator,
the strict equality operator always considers operands of different types to be
different.
{{EmbedInteractiveExample("pages/js/expressions-strict-equality.html")}}
## Syntax
```js-nolint
x === y
```
## Description
The strict equality operators (`===` and `!==`) provide the [IsStrictlyEqual](/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#strict_equality_using) semantic.
- If the operands are of different types, return `false`.
- If both operands are objects, return `true` only if they refer to the
same object.
- If both operands are `null` or both operands are `undefined`,
return `true`.
- If either operand is `NaN`, return `false`.
- Otherwise, compare the two operand's values:
- Numbers must have the same numeric values. `+0` and `-0`
are considered to be the same value.
- Strings must have the same characters in the same order.
- Booleans must be both `true` or both `false`.
The most notable difference between this operator and the [equality](/en-US/docs/Web/JavaScript/Reference/Operators/Equality)
(`==`) operator is that if the operands are of different types, the
`==` operator attempts to convert them to the same type before comparing.
## Examples
### Comparing operands of the same type
```js
"hello" === "hello"; // true
"hello" === "hola"; // false
3 === 3; // true
3 === 4; // false
true === true; // true
true === false; // false
null === null; // true
```
### Comparing operands of different types
```js
"3" === 3; // false
true === 1; // false
null === undefined; // false
3 === new Number(3); // false
```
### Comparing objects
```js
const object1 = {
key: "value",
};
const object2 = {
key: "value",
};
console.log(object1 === object2); // false
console.log(object1 === object1); // true
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Equality (`==`)](/en-US/docs/Web/JavaScript/Reference/Operators/Equality)
- [Inequality (`!=`)](/en-US/docs/Web/JavaScript/Reference/Operators/Inequality)
- [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/assignment/index.md | ---
title: Assignment (=)
slug: Web/JavaScript/Reference/Operators/Assignment
page-type: javascript-operator
browser-compat: javascript.operators.assignment
---
{{jsSidebar("Operators")}}
The **assignment (`=`)** operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables.
{{EmbedInteractiveExample("pages/js/expressions-assignment.html")}}
## Syntax
```js-nolint
x = y
```
### Parameters
- `x`
- : A valid assignment target, including an [identifier](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#identifiers) or a [property accessor](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors). It can also be a [destructuring assignment pattern](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment).
- `y`
- : An expression specifying the value to be assigned to `x`.
### Return value
The value of `y`.
### Exceptions
- {{jsxref("ReferenceError")}}
- : Thrown in strict mode if assigning to an identifier that is not declared in the scope.
- {{jsxref("TypeError")}}
- : Thrown in strict mode if assigning to a [property that is not modifiable](/en-US/docs/Web/JavaScript/Reference/Strict_mode#failing_to_assign_to_object_properties).
## Description
The assignment operator is completely different from the equals (`=`) sign used as syntactic separators in other locations, which include:
- Initializers of [`var`](/en-US/docs/Web/JavaScript/Reference/Statements/var), [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let), and [`const`](/en-US/docs/Web/JavaScript/Reference/Statements/const) declarations
- Default values of [destructuring](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#default_value)
- [Default parameters](/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters)
- Initializers of [class fields](/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields)
All these places accept an assignment expression on the right-hand side of the `=`, so if you have multiple equals signs chained together:
```js-nolint
const x = y = 5;
```
This is equivalent to:
```js
const x = (y = 5);
```
Which means `y` must be a pre-existing variable, and `x` is a newly declared `const` variable. `y` is assigned the value `5`, and `x` is initialized with the value of the `y = 5` expression, which is also `5`. If `y` is not a pre-existing variable, a global variable `y` is implicitly created in [non-strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode), or a {{jsxref("ReferenceError")}} is thrown in strict mode. To declare two variables within the same declaration, use:
```js
const x = 5,
y = 5;
```
## Examples
### Simple assignment and chaining
```js
let x = 5;
let y = 10;
let z = 25;
x = y; // x is 10
x = y = z; // x, y and z are all 25
```
### Value of assignment expressions
The assignment expression itself evaluates to the value of the right-hand side, so you can log the value and assign to a variable at the same time.
```js-nolint
let x;
console.log(x); // undefined
console.log(x = 2); // 2
console.log(x); // 2
```
### Unqualified identifier assignment
The global object sits at the top of the scope chain. When attempting to resolve a name to a value, the scope chain is searched. This means that properties on the global object are conveniently visible from every scope, without having to qualify the names with `globalThis.` or `window.` or `global.`.
Because the global object has a `String` property (`Object.hasOwn(globalThis, "String")`), you can use the following code:
```js
function foo() {
String("s"); // The function `String` is globally available
}
```
So the global object will ultimately be searched for unqualified identifiers. You don't have to type `globalThis.String`; you can just type the unqualified `String`. To make this feature more conceptually consistent, assignment to unqualified identifiers will assume you want to create a property with that name on the global object (with `globalThis.` omitted), if there is no variable of the same name declared in the scope chain.
```js
foo = "f"; // In non-strict mode, assumes you want to create a property named `foo` on the global object
Object.hasOwn(globalThis, "foo"); // true
```
In [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode#assigning_to_undeclared_variables), assignment to an unqualified identifier in strict mode will result in a `ReferenceError`, to avoid the accidental creation of properties on the global object.
Note that the implication of the above is that, contrary to popular misinformation, JavaScript does not have implicit or undeclared variables. It just conflates the global object with the global scope and allows omitting the global object qualifier during property creation.
### Assignment with destructuring
The left-hand side of can also be an assignment pattern. This allows assigning to multiple variables at once.
```js
const result = /(a+)(b+)(c+)/.exec("aaabcc");
let a = "",
b = "",
c = "";
[, 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
- [Assignment operators in the JS guide](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#assignment_operators)
- [Destructuring assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/yield/index.md | ---
title: yield
slug: Web/JavaScript/Reference/Operators/yield
page-type: javascript-operator
browser-compat: javascript.operators.yield
---
{{jsSidebar("Operators")}}
The **`yield`** operator is used to pause and resume a [generator function](/en-US/docs/Web/JavaScript/Reference/Statements/function*).
{{EmbedInteractiveExample("pages/js/expressions-yield.html", "taller")}}
## Syntax
```js-nolint
yield
yield expression
```
### Parameters
- `expression` {{optional_inline}}
- : The value to yield from the generator function via [the iterator protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol). If omitted, `undefined` is yielded.
### Return value
Returns the optional value passed to the generator's `next()` method to resume its execution.
> **Note:** This means `next()` is asymmetric: it always sends a value to the currently suspended `yield`, but returns the operand of the next `yield`. The argument passed to the first `next()` call cannot be retrieved because there's no currently suspended `yield`.
## Description
The `yield` keyword pauses generator function execution and the value of the expression following the `yield` keyword is returned to the generator's caller. It can be thought of as a generator-based version of the `return` keyword.
`yield` can only be used directly within the generator function that contains it. It cannot be used within nested functions.
Calling a generator function constructs a {{jsxref("Generator")}} object. Each time the generator's {{jsxref("Generator/next", "next()")}} method is called, the generator resumes execution, and runs until it reaches one of the following:
- A `yield` expression. In this case, the generator pauses, and the `next()` method return an [iterator result](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol) object with two properties: `value` and `done`. The `value` property is the value of the expression after the `yield` operator, and `done` is `false`, indicating that the generator function has not fully completed.
- The end of the generator function. In this case, execution of the generator ends, and the `next()` method returns an iterator result object where the `value` is {{jsxref("undefined")}} and `done` is `true`.
- A {{jsxref("Statements/return", "return")}} statement. In this case, execution of the generator ends, and the `next()` method returns an iterator result object where the `value` is the specified return value and `done` is `true`.
- A {{jsxref("Statements/throw", "throw")}} statement. In this case, execution of the generator halts entirely, and the `next()` method throws the specified exception.
Once paused on a `yield` expression, the generator's code execution remains paused until the generator's `next()` method is called again. If an optional value is passed to the generator's `next()` method, that value becomes the value returned by the generator's current `yield` operation. The first `next()` call does not have a corresponding suspended `yield` operation, so there's no way to get the argument passed to the first `next()` call.
If the generator's {{jsxref("Generator/return", "return()")}} or {{jsxref("Generator/throw", "throw()")}} method is called, it acts as if a {{jsxref("Statements/return", "return")}} or {{jsxref("Statements/throw", "throw")}} statement was executed at the paused `yield` expression. You can use {{jsxref("Statements/try...catch", "try...catch...finally")}} within the generator function body to handle these early completions. If the `return()` or `throw()` method is called but there's no suspended `yield` expression (because `next()` has not been called yet, or because the generator has already completed), then the early completions cannot be handled and always terminate the generator.
## Examples
### Using yield
The following code is the declaration of an example generator function.
```js
function* countAppleSales() {
const saleList = [3, 7, 5];
for (let i = 0; i < saleList.length; i++) {
yield saleList[i];
}
}
```
Once a generator function is defined, it can be used by constructing an iterator as shown.
```js
const appleStore = countAppleSales(); // Generator { }
console.log(appleStore.next()); // { value: 3, done: false }
console.log(appleStore.next()); // { value: 7, done: false }
console.log(appleStore.next()); // { value: 5, done: false }
console.log(appleStore.next()); // { value: undefined, done: true }
```
You can also send a value with `next(value)` into the generator. `step` evaluates as a return value of the `yield` expression β although the value passed to the generator's `next()` method the first time `next()` is called is ignored.
```js
function* counter(value) {
while (true) {
const step = yield value++;
if (step) {
value += step;
}
}
}
const generatorFunc = counter(0);
console.log(generatorFunc.next().value); // 0
console.log(generatorFunc.next().value); // 1
console.log(generatorFunc.next().value); // 2
console.log(generatorFunc.next().value); // 3
console.log(generatorFunc.next(10).value); // 14
console.log(generatorFunc.next().value); // 15
console.log(generatorFunc.next(10).value); // 26
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
- {{jsxref("Statements/function*", "function*")}}
- [`function*` expression](/en-US/docs/Web/JavaScript/Reference/Operators/function*)
- {{jsxref("Operators/yield*", "yield*")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/unsigned_right_shift_assignment/index.md | ---
title: Unsigned right shift assignment (>>>=)
slug: Web/JavaScript/Reference/Operators/Unsigned_right_shift_assignment
page-type: javascript-operator
browser-compat: javascript.operators.unsigned_right_shift_assignment
---
{{jsSidebar("Operators")}}
The **unsigned right shift assignment (`>>>=`)** operator performs [unsigned right shift](/en-US/docs/Web/JavaScript/Reference/Operators/Unsigned_right_shift) on the two operands and assigns the result to the left operand.
{{EmbedInteractiveExample("pages/js/expressions-unsigned-right-shift-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 unsigned right shift assignment
```js
let a = 5; // (00000000000000000000000000000101)
a >>>= 2; // 1 (00000000000000000000000000000001)
let b = -5; // (-00000000000000000000000000000101)
b >>>= 2; // 1073741822 (00111111111111111111111111111110)
let c = 5n;
c >>>= 2n; // 1n
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Assignment operators in the JS guide](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#assignment_operators)
- [Unsigned right shift (`>>>`)](/en-US/docs/Web/JavaScript/Reference/Operators/Unsigned_right_shift)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/spread_syntax/index.md | ---
title: Spread syntax (...)
slug: Web/JavaScript/Reference/Operators/Spread_syntax
page-type: javascript-operator
browser-compat: javascript.operators.spread
---
{{jsSidebar("Operators")}}
The **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.
Spread syntax looks exactly like rest syntax. In a way, spread syntax is the opposite of rest syntax. Spread syntax "expands" an array into its elements, while rest syntax collects multiple elements and "condenses" them into a single element. See [rest parameters](/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters) and [rest property](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#rest_property).
{{EmbedInteractiveExample("pages/js/expressions-spreadsyntax.html")}}
## Syntax
```js-nolint
myFunction(a, ...iterableObj, b)
[1, ...iterableObj, '4', 'five', 6]
{ ...obj, key: 'value' }
```
## Description
Spread syntax can be used when all elements from an object or array need to be included in a new array or object, or should be applied one-by-one in a function call's arguments list. There are three distinct places that accept the spread syntax:
- [Function arguments](#spread_in_function_calls) list (`myFunction(a, ...iterableObj, b)`)
- [Array literals](#spread_in_array_literals) (`[1, ...iterableObj, '4', 'five', 6]`)
- [Object literals](#spread_in_object_literals) (`{ ...obj, key: 'value' }`)
Although the syntax looks the same, they come with slightly different semantics.
Only [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) values, like {{jsxref("Array")}} and {{jsxref("String")}}, can be spread in [array literals](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#array_literals) and argument lists. Many objects are not iterable, including all [plain objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) that lack a [`Symbol.iterator`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator) method:
```js example-bad
const obj = { key1: "value1" };
const array = [...obj]; // TypeError: obj is not iterable
```
On the other hand, spreading in [object literals](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) [enumerates](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties#traversing_object_properties) the own properties of the value. For typical arrays, all indices are enumerable own properties, so arrays can be spread into objects.
```js
const array = [1, 2, 3];
const obj = { ...array }; // { 0: 1, 1: 2, 2: 3 }
```
All [primitives](/en-US/docs/Web/JavaScript/Data_structures#primitive_values) can be spread in objects. Only strings have enumerable own properties, and spreading anything else doesn't create properties on the new object.
```js
const obj = { ...true, ..."test", ...10 };
// { '0': 't', '1': 'e', '2': 's', '3': 't' }
```
When using spread syntax for function calls, be aware of the possibility of exceeding the JavaScript engine's argument length limit. See {{jsxref("Function.prototype.apply()")}} for more details.
## Examples
### Spread in function calls
#### Replace apply()
It is common to use {{jsxref("Function.prototype.apply()")}} in cases where you want to
use the elements of an array as arguments to a function.
```js
function myFunction(x, y, z) {}
const args = [0, 1, 2];
myFunction.apply(null, args);
```
With spread syntax the above can be written as:
```js
function myFunction(x, y, z) {}
const args = [0, 1, 2];
myFunction(...args);
```
Any argument in the argument list can use spread syntax, and the spread syntax can be
used multiple times.
```js
function myFunction(v, w, x, y, z) {}
const args = [0, 1];
myFunction(-1, ...args, 2, ...[3]);
```
#### Apply for new operator
When calling a constructor with {{jsxref("Operators/new", "new")}}, it's not possible to **directly** use an array and `apply()`, because `apply()` _calls_ the target function instead of _constructing_ it, which means, among other things, that [`new.target`](/en-US/docs/Web/JavaScript/Reference/Operators/new.target) will be `undefined`. However, an array can be easily used with `new` thanks to spread syntax:
```js
const dateFields = [1970, 0, 1]; // 1 Jan 1970
const d = new Date(...dateFields);
```
### Spread in array literals
#### A more powerful array literal
Without spread syntax, the array literal syntax is no longer sufficient to create a new array using an existing array as one part of it. Instead, imperative code must be used using a combination of methods, including {{jsxref("Array/push", "push()")}}, {{jsxref("Array/splice", "splice()")}}, {{jsxref("Array/concat", "concat()")}}, etc. With spread syntax, this becomes much more succinct:
```js
const parts = ["shoulders", "knees"];
const lyrics = ["head", ...parts, "and", "toes"];
// ["head", "shoulders", "knees", "and", "toes"]
```
Just like spread for argument lists, `...` can be used anywhere in the array literal, and may be used more than once.
#### Copying an array
You can use spread syntax to make a {{Glossary("shallow copy")}} of an array. Each array element retains its identity without getting copied.
```js
const arr = [1, 2, 3];
const arr2 = [...arr]; // like arr.slice()
arr2.push(4);
// arr2 becomes [1, 2, 3, 4]
// arr remains unaffected
```
Spread syntax effectively goes one level deep while copying an array. Therefore, it may be unsuitable for copying multidimensional arrays. The same is true with {{jsxref("Object.assign()")}} β no native operation in JavaScript does a deep clone. The web API method {{domxref("structuredClone()")}} allows deep copying values of certain [supported types](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm#supported_types). See [shallow copy](/en-US/docs/Glossary/Shallow_copy) for more details.
```js example-bad
const a = [[1], [2], [3]];
const b = [...a];
b.shift().shift();
// 1
// Oh no! Now array 'a' is affected as well:
console.log(a);
// [[], [2], [3]]
```
#### A better way to concatenate arrays
{{jsxref("Array.prototype.concat()")}} is often used to concatenate an array to the end of an existing array. Without spread syntax, this is done as:
```js
let arr1 = [0, 1, 2];
const arr2 = [3, 4, 5];
// Append all items from arr2 onto arr1
arr1 = arr1.concat(arr2);
```
With spread syntax this becomes:
```js
let arr1 = [0, 1, 2];
const arr2 = [3, 4, 5];
arr1 = [...arr1, ...arr2];
// arr1 is now [0, 1, 2, 3, 4, 5]
```
{{jsxref("Array.prototype.unshift()")}} is often used to insert an array of values at the start of an existing array. Without spread syntax, this is done as:
```js
const arr1 = [0, 1, 2];
const arr2 = [3, 4, 5];
// Prepend all items from arr2 onto arr1
Array.prototype.unshift.apply(arr1, arr2);
console.log(arr1); // [3, 4, 5, 0, 1, 2]
```
With spread syntax, this becomes:
```js
let arr1 = [0, 1, 2];
const arr2 = [3, 4, 5];
arr1 = [...arr2, ...arr1];
console.log(arr1); // [3, 4, 5, 0, 1, 2]
```
> **Note:** Unlike `unshift()`, this creates a new `arr1`, instead of modifying the original `arr1` array in-place.
#### Conditionally adding values to an array
You can make an element present or absent in an array literal, depending on a condition, using a [conditional operator](/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator).
```js
const isSummer = false;
const fruits = ["apple", "banana", ...(isSummer ? ["watermelon"] : [])];
// ['apple', 'banana']
```
When the condition is `false`, we spread an empty array, so that nothing gets added to the final array. Note that this is different from the following:
```js
const fruits = ["apple", "banana", isSummer ? "watermelon" : undefined];
// ['apple', 'banana', undefined]
```
In this case, an extra `undefined` element is added when `isSummer` is `false`, and this element will be visited by methods such as {{jsxref("Array.prototype.map()")}}.
### Spread in object literals
#### Copying and merging objects
You can use spread syntax to merge multiple objects into one new object.
```js
const obj1 = { foo: "bar", x: 42 };
const obj2 = { bar: "baz", y: 13 };
const mergedObj = { ...obj1, ...obj2 };
// { foo: "bar", x: 42, bar: "baz", y: 13 }
```
A single spread creates a shallow copy of the original object (but without non-enumerable properties and without copying the prototype), similar to [copying an array](#copying_an_array).
```js
const clonedObj = { ...obj1 };
// { foo: "bar", x: 42 }
```
#### Overriding properties
When one object is spread into another object, or when multiple objects are spread into one object, and properties with identical names are encountered, the property takes the last value assigned while remaining in the position it was originally set.
```js
const obj1 = { foo: "bar", x: 42 };
const obj2 = { foo: "baz", y: 13 };
const mergedObj = { x: 41, ...obj1, ...obj2, y: 9 }; // { x: 42, foo: "baz", y: 9 }
```
#### Conditionally adding properties to an object
You can make an element present or absent in an object literal, depending on a condition, using a [conditional operator](/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator).
```js
const isSummer = false;
const fruits = {
apple: 10,
banana: 5,
...(isSummer ? { watermelon: 30 } : {}),
};
// { apple: 10, banana: 5 }
```
The case where the condition is `false` is an empty object, so that nothing gets spread into the final object. Note that this is different from the following:
```js
const fruits = {
apple: 10,
banana: 5,
watermelon: isSummer ? 30 : undefined,
};
// { apple: 10, banana: 5, watermelon: undefined }
```
In this case, the `watermelon` property is always present and will be visited by methods such as {{jsxref("Object.keys()")}}.
Because primitives can be spread into objects as well, and from the observation that all {{Glossary("falsy")}} values do not have enumerable properties, you can simply use a [logical AND](/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND) operator:
```js
const isSummer = false;
const fruits = {
apple: 10,
banana: 5,
...(isSummer && { watermelon: 30 }),
};
```
In this case, if `isSummer` is any falsy value, no property will be created on the `fruits` object.
#### Comparing with Object.assign()
Note that {{jsxref("Object.assign()")}} can be used to mutate an object, whereas spread syntax can't.
```js
const obj1 = { foo: "bar", x: 42 };
Object.assign(obj1, { x: 1337 });
console.log(obj1); // { foo: "bar", x: 1337 }
```
In addition, {{jsxref("Object.assign()")}} triggers setters on the target object, whereas spread syntax does not.
```js
const objectAssign = Object.assign(
{
set foo(val) {
console.log(val);
},
},
{ foo: 1 },
);
// Logs "1"; objectAssign.foo is still the original setter
const spread = {
set foo(val) {
console.log(val);
},
...{ foo: 1 },
};
// Nothing is logged; spread.foo is 1
```
You cannot naively re-implement the {{jsxref("Object.assign()")}} function through a single spreading:
```js
const obj1 = { foo: "bar", x: 42 };
const obj2 = { foo: "baz", y: 13 };
const merge = (...objects) => ({ ...objects });
const mergedObj1 = merge(obj1, obj2);
// { 0: { foo: 'bar', x: 42 }, 1: { foo: 'baz', y: 13 } }
const mergedObj2 = merge({}, obj1, obj2);
// { 0: {}, 1: { foo: 'bar', x: 42 }, 2: { foo: 'baz', y: 13 } }
```
In the above example, the spread syntax does not work as one might expect: it spreads an _array_ of arguments into the object literal, due to the rest parameter. Here is an implementation of `merge` using the spread syntax, whose behavior is similar to {{jsxref("Object.assign()")}}, except that it doesn't trigger setters, nor mutates any object:
```js
const obj1 = { foo: "bar", x: 42 };
const obj2 = { foo: "baz", y: 13 };
const merge = (...objects) =>
objects.reduce((acc, cur) => ({ ...acc, ...cur }));
const mergedObj1 = merge(obj1, obj2);
// { foo: 'baz', x: 42, y: 13 }
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Rest parameters](/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters)
- [Rest property](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#rest_property)
- {{jsxref("Function.prototype.apply()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/right_shift_assignment/index.md | ---
title: Right shift assignment (>>=)
slug: Web/JavaScript/Reference/Operators/Right_shift_assignment
page-type: javascript-operator
browser-compat: javascript.operators.right_shift_assignment
---
{{jsSidebar("Operators")}}
The **right shift assignment (`>>=`)** operator performs [right shift](/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift) on the two operands and assigns the result to the left operand.
{{EmbedInteractiveExample("pages/js/expressions-right-shift-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 right shift assignment
```js
let a = 5; // (00000000000000000000000000000101)
a >>= 2; // 1 (00000000000000000000000000000001)
let b = -5; // (-00000000000000000000000000000101)
b >>= 2; // -2 (-00000000000000000000000000000010)
let c = 5n;
c >>= 2n; // 1n
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Assignment operators in the JS guide](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#assignment_operators)
- [Right shift (`>>`)](/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/async_function_star_/index.md | ---
title: async function* expression
slug: Web/JavaScript/Reference/Operators/async_function*
page-type: javascript-operator
browser-compat: javascript.operators.async_generator_function
---
{{jsSidebar("Operators")}}
The **`async function*`** keywords can be used to define an async generator function inside an expression.
You can also define async generator functions using the [`async function*` declaration](/en-US/docs/Web/JavaScript/Reference/Statements/async_function*).
{{EmbedInteractiveExample("pages/js/expressions-async-function-asterisk.html", "taller")}}
## 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 create an ad-hoc [async iterable object](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols). See also the chapter about [functions](/en-US/docs/Web/JavaScript/Reference/Functions) for more information.
## Examples
### Using async function\* expression
The following example defines an unnamed asynchronous generator function and assigns it to `x`. The function yields the square of its argument:
```js
const x = async function* (y) {
yield Promise.resolve(y * y);
};
x(6)
.next()
.then((res) => console.log(res.value)); // 36
```
## 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("AsyncGeneratorFunction")}}
- [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
- {{jsxref("Operators/yield", "yield")}}
- {{jsxref("Operators/yield*", "yield*")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/unary_negation/index.md | ---
title: Unary negation (-)
slug: Web/JavaScript/Reference/Operators/Unary_negation
page-type: javascript-operator
browser-compat: javascript.operators.unary_negation
---
{{jsSidebar("Operators")}}
The **unary negation (`-`)** operator precedes its operand and negates it.
{{EmbedInteractiveExample("pages/js/expressions-unary-negation.html")}}
## Syntax
```js-nolint
-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 negation if the operand becomes a BigInt; otherwise, it performs number negation.
## Examples
### Negating numbers
```js
const x = 3;
const y = -x;
// y is -3; x is 3
```
### Negating non-numbers
The unary negation operator can convert a non-number into a number.
```js
const x = "4";
const y = -x;
// y is -4
```
BigInts can be negated using the unary negation operator.
```js
const x = 4n;
const y = -x;
// y is -4n
```
## 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)
- [Decrement (`--`)](/en-US/docs/Web/JavaScript/Reference/Operators/Decrement)
- [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/increment/index.md | ---
title: Increment (++)
slug: Web/JavaScript/Reference/Operators/Increment
page-type: javascript-operator
browser-compat: javascript.operators.increment
---
{{jsSidebar("Operators")}}
The **increment (`++`)** operator increments (adds one to) its operand and returns the value before or after the increment, depending on where the operator is placed.
{{EmbedInteractiveExample("pages/js/expressions-increment.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 increment if the operand becomes a BigInt; otherwise, it performs number increment.
If used postfix, with operator after operand (for example, `x++`), the increment operator increments and returns the value before incrementing.
If used prefix, with operator before operand (for example, `++x`), the increment operator increments and returns the value after incrementing.
The increment 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 increment operators together.
```js-nolint example-bad
++(++x); // SyntaxError: Invalid left-hand side expression in prefix operation
```
## Examples
### Postfix increment
```js
let x = 3;
const y = x++;
// x is 4; y is 3
let x2 = 3n;
const y2 = x2++;
// x2 is 4n; y2 is 3n
```
### Prefix increment
```js
let x = 3;
const y = ++x;
// x is 4; y is 4
let x2 = 3n;
const y2 = ++x2;
// x2 is 4n; y2 is 4n
```
## 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)
- [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)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/bitwise_or_assignment/index.md | ---
title: Bitwise OR assignment (|=)
slug: Web/JavaScript/Reference/Operators/Bitwise_OR_assignment
page-type: javascript-operator
browser-compat: javascript.operators.bitwise_or_assignment
---
{{jsSidebar("Operators")}}
The **bitwise OR assignment (`|=`)** operator performs [bitwise OR](/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR) on the two operands and assigns the result to the left operand.
{{EmbedInteractiveExample("pages/js/expressions-bitwise-or-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 OR assignment
```js
let a = 5;
a |= 2; // 7
// 5: 00000000000000000000000000000101
// 2: 00000000000000000000000000000010
// -----------------------------------
// 7: 00000000000000000000000000000111
let b = 5n;
b |= 2n; // 7n
```
## 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 OR (`|`)](/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR)
- [Logical OR assignment (`||=`)](/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR_assignment)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/logical_or_assignment/index.md | ---
title: Logical OR assignment (||=)
slug: Web/JavaScript/Reference/Operators/Logical_OR_assignment
page-type: javascript-operator
browser-compat: javascript.operators.logical_or_assignment
---
{{jsSidebar("Operators")}}
The **logical OR assignment (`||=`)** operator only evaluates the right operand and assigns to the left if the left operand is {{Glossary("falsy")}}.
{{EmbedInteractiveExample("pages/js/expressions-logical-or-assignment.html")}}
## Syntax
```js-nolint
x ||= y
```
## Description
Logical OR assignment [_short-circuits_](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence#short-circuiting), meaning that `x ||= y` is equivalent to `x || (x = y)`, except that the expression `x` is only evaluated once.
No assignment is performed if the left-hand side is not falsy, due to short-circuiting of the [logical OR](/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR) operator. For example, the following does not throw an error, despite `x` being `const`:
```js
const x = 1;
x ||= 2;
```
Neither would the following trigger the setter:
```js
const x = {
get value() {
return 1;
},
set value(v) {
console.log("Setter called");
},
};
x.value ||= 2;
```
In fact, if `x` is not falsy, `y` is not evaluated at all.
```js
const x = 1;
x ||= console.log("y evaluated");
// Logs nothing
```
## Examples
### Setting default content
If the "lyrics" element is empty, display a default value:
```js
document.getElementById("lyrics").textContent ||= "No lyrics.";
```
Here the short-circuit is especially beneficial, since the element will not be updated unnecessarily and won't cause unwanted side-effects such as additional parsing or rendering work, or loss of focus, etc.
Note: Pay attention to the value returned by the API you're checking against. If an empty string is returned (a {{Glossary("falsy")}} value), `||=` must be used, so that "No lyrics." is displayed instead of a blank space. However, if the API returns [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) or
{{jsxref("undefined")}} in case of blank content, [`??=`](/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_assignment) should be used instead.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Logical OR (`||`)](/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR)
- [Nullish coalescing operator (`??`)](/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing)
- [Bitwise OR assignment (`|=`)](/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR_assignment)
- {{Glossary("Truthy")}}
- {{Glossary("Falsy")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/subtraction/index.md | ---
title: Subtraction (-)
slug: Web/JavaScript/Reference/Operators/Subtraction
page-type: javascript-operator
browser-compat: javascript.operators.subtraction
---
{{jsSidebar("Operators")}}
The **subtraction (`-`)** operator subtracts the two operands, producing their difference.
{{EmbedInteractiveExample("pages/js/expressions-subtraction.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 subtraction if both operands become BigInts; otherwise, it performs number subtraction. A {{jsxref("TypeError")}} is thrown if one operand becomes a BigInt but the other becomes a number.
## Examples
### Subtraction with numbers
```js
// Number - Number -> subtraction
5 - 3; // 2
// Number - Number -> subtraction
3 - 5; // -2
```
### Subtraction with non-numbers
```js
// String - Number -> subtraction
"foo" - 3; // NaN; "foo" is converted to the number NaN
// Number - String -> subtraction
5 - "3"; // 2; "3" is converted to the number 3
```
### Subtraction with BigInts
```js
// BigInt - BigInt -> subtraction
2n - 1n; // 1n
```
You cannot mix BigInt and number operands in subtraction.
```js example-bad
2n - 1; // TypeError: Cannot mix BigInt and other types, use explicit conversions
2 - 1n; // TypeError: Cannot mix BigInt and other types, use explicit conversions
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Addition (`+`)](/en-US/docs/Web/JavaScript/Reference/Operators/Addition)
- [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)
- [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)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/strict_inequality/index.md | ---
title: Strict inequality (!==)
slug: Web/JavaScript/Reference/Operators/Strict_inequality
page-type: javascript-operator
browser-compat: javascript.operators.strict_inequality
---
{{jsSidebar("Operators")}}
The **strict inequality (`!==`)** operator checks whether its two operands are
not equal, returning a Boolean result. Unlike the [inequality](/en-US/docs/Web/JavaScript/Reference/Operators/Inequality)
operator, the strict inequality operator always considers operands of different types to
be different.
{{EmbedInteractiveExample("pages/js/expressions-strict-inequality.html")}}
## Syntax
```js-nolint
x !== y
```
## Description
The strict inequality operator checks whether its operands are not equal.
It is the negation of the
[strict equality](/en-US/docs/Web/JavaScript/Reference/Operators/Strict_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
[strict equality](/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality) operator.
Like the strict equality operator, the strict inequality operator will always consider
operands of different types to be different:
```js
3 !== "3"; // true
```
## Examples
### Comparing operands of the same type
```js
"hello" !== "hello"; // false
"hello" !== "hola"; // true
3 !== 3; // false
3 !== 4; // true
true !== true; // false
true !== false; // true
null !== null; // false
```
### Comparing operands of different types
```js
"3" !== 3; // true
true !== 1; // true
null !== undefined; // true
```
### Comparing 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)
- [Inequality (`!=`)](/en-US/docs/Web/JavaScript/Reference/Operators/Inequality)
- [Strict equality (`===`)](/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/import.meta/index.md | ---
title: import.meta
slug: Web/JavaScript/Reference/Operators/import.meta
page-type: javascript-language-feature
browser-compat: javascript.operators.import_meta
---
{{jsSidebar("Operators")}}
The **`import.meta`** meta-property exposes context-specific metadata to a JavaScript module. It contains information about the module, such as the module's URL.
## Syntax
```js-nolint
import.meta
```
### Value
The `import.meta` object is created by the host environment, as an extensible [`null`-prototype](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) object where all properties are writable, configurable, and enumerable. The spec doesn't specify any properties to be defined on it, but hosts usually implement the following properties:
- `url`
- : The full URL to the module, includes query parameters and/or hash (following the `?` or `#`). In browsers, this is either the URL from which the script was obtained (for external scripts), or the URL of the containing document (for inline scripts). In Node.js, this is the file path (including the `file://` protocol).
- [`resolve`](/en-US/docs/Web/JavaScript/Reference/Operators/import.meta/resolve)
- : Resolves a module specifier to a URL using the current module's URL as base.
## Description
The `import.meta` syntax consists of the keyword `import`, a dot, and the identifier `meta`. Because `import` is a [reserved word](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#reserved_words), not an identifier, this is not a [property accessor](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors), but a special expression syntax.
The `import.meta` meta-property is available in JavaScript modules; using `import.meta` outside of a module (including [direct `eval()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#direct_and_indirect_eval) within a module) is a syntax error.
## Examples
### Passing query parameters
Using query parameters in the `import` specifier allows module-specific argument passing, which may be complementary to reading parameters from the application-wide [`window.location`](/en-US/docs/Web/API/Window/location) (or on Node.js, through `process.argv`). For example, with the following HTML:
```html
<script type="module">
import "./index.mjs?someURLInfo=5";
</script>
```
The `index.mjs` module is able to retrieve the `someURLInfo` parameter through `import.meta`:
```js
// index.mjs
new URL(import.meta.url).searchParams.get("someURLInfo"); // 5
```
The same applies when a module imports another:
```js
// index.mjs
import "./index2.mjs?someURLInfo=5";
// index2.mjs
new URL(import.meta.url).searchParams.get("someURLInfo"); // 5
```
The ES module implementation in Node.js supports resolving module specifiers containing query parameters (or the hash), as in the latter example. However, you cannot use queries or hashes when the module is specified through the CLI command (like `node index.mjs?someURLInfo=5`), because the CLI entrypoint uses a more CommonJS-like resolution mode, treating the path as a file path rather than a URL. To pass parameters to the entrypoint module, use CLI arguments and read them through `process.argv` instead (like `node index.mjs --someURLInfo=5`).
### Resolving a file relative to the current one
In Node.js CommonJS modules, there's a `__dirname` variable that contains the absolute path to the folder containing current module, which is useful for resolving relative paths. However, ES modules cannot have contextual variables except for `import.meta`. Therefore, to resolve a relative file you can use `import.meta.url`. Note that this uses URLs rather than filesystem paths.
Before (CommonJS):
```js
const fs = require("fs/promises");
const path = require("path");
const filePath = path.join(__dirname, "someFile.txt");
fs.readFile(filePath, "utf8").then(console.log);
```
After (ES modules):
```js
import fs from "node:fs/promises";
const fileURL = new URL("./someFile.txt", import.meta.url);
fs.readFile(fileURL, "utf8").then(console.log);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Statements/import", "import")}}
- {{jsxref("Statements/export", "export")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators/import.meta | data/mdn-content/files/en-us/web/javascript/reference/operators/import.meta/resolve/index.md | ---
title: import.meta.resolve()
slug: Web/JavaScript/Reference/Operators/import.meta/resolve
page-type: javascript-language-feature
browser-compat: javascript.operators.import_meta.resolve
---
{{jsSidebar("Operators")}}
**`import.meta.resolve()`** is a built-in function defined on the [`import.meta`](/en-US/docs/Web/JavaScript/Reference/Operators/import.meta) object of a JavaScript module that resolves a module specifier to a URL using the current module's URL as base.
## Syntax
```js-nolint
import.meta.resolve(moduleName)
```
### Parameters
- `moduleName`
- : A string that specifies a potentially importable module. This may be a relative path (such as `"./lib/helper.js"`), a bare name (such as `"my-module"`), or an absolute URL (such as `"https://example.com/lib/helper.js"`).
### Return value
Returns a string corresponding to the path that would be imported if the argument were passed to [`import()`](/en-US/docs/Web/JavaScript/Reference/Operators/import).
## Description
`import.meta.resolve()` allows a script to access the _module specifier resolution_ algorithm for a name, like this:
```js
// Script at https://example.com/main.js
const helperPath = import.meta.resolve("./lib/helper.js");
console.log(helperPath); // "https://example.com/lib/helper.js"
```
Note that `import.meta.resolve()` only performs resolution and does not attempt to load or import the resulting path. (The [explainer for the specification](https://gist.github.com/domenic/f2a0a9cb62d499bcc4d12aebd1c255ab#sync-vs-async) describes the reasoning for this behavior.) Therefore, its return value is the same _regardless of whether the returned path corresponds to a file that exists, and regardless of whether that file contains valid code for a module_.
It is different from [dynamic import](/en-US/docs/Web/JavaScript/Reference/Operators/import), because although both accept a module specifier as the first argument, `import.meta.resolve()` returns the path that _would be imported_ without making any attempt to access that path. Therefore, the following two are effectively the same code:
```js
// Approach 1
console.log(await import("./lib/helper.js"));
// Approach 2
const helperPath = import.meta.resolve("./lib/helper.js");
console.log(await import(helperPath));
```
However, even if `"./lib/helper.js"` cannot be successfully imported, the second snippet will not encounter an error until it attempts to perform the import on line 2.
### Bare module names
You can pass a bare module name (also known as a bare module specifier) to `import.meta.resolve()`, as long as module resolution is defined for the name. For example, you can define this using an [import map](/en-US/docs/Web/JavaScript/Guide/Modules#importing_modules_using_import_maps) inside a browser:
```html
<!-- index.html -->
<script type="importmap">
{
"imports": {
"my-module": "./modules/my-module/index.js"
}
}
</script>
<script type="module">
const moduleEntryPath = import.meta.resolve("my-module");
console.log(moduleEntryPath);
</script>
```
Again, since this snippet does not try to import `moduleEntryPath` β neither does the import map β it prints the resolved URL regardless of whether `./modules/my-module/index.js` actually exists.
### Comparison with new URL()
The [`URL()`](/en-US/docs/Web/API/URL/URL) constructor accepts a second _base URL_ argument. When the first argument is a relative path and the base URL is [`import.meta.url`](/en-US/docs/Web/JavaScript/Reference/Operators/import.meta#value), the effect is similar to `import.meta.resolve()`.
```js
const helperPath = new URL("./lib/helper.js", import.meta.url).href;
console.log(helperPath);
```
This is also a useful replacement syntax when targeting older browsers. However, there are some differences:
- `import.meta.resolve()` returns a string, while `new URL()` returns a `URL` object. It is possible to use [`href`](/en-US/docs/Web/API/URL/href) or [`toString()`](/en-US/docs/Web/API/URL/toString) on the constructed `URL`, but this may still not produce the exact same result in some JavaScript environments or when using tools like bundlers to statically analyze the code.
- `import.meta.resolve()` is aware of additional resolution configurations, such as resolving bare module names using import maps, as described above. `new URL()` is not aware of import maps and treats bare module names as relative paths (i.e. `new URL("my-module", import.meta.url)` means `new URL("./my-module", import.meta.url)`).
Some tools recognize `new URL("./lib/helper.js", import.meta.url).href` as a dependency on `"./lib/helper.js"` (similar to an import), and take this into account for features like bundling, rewriting imports for moved files, "go to source" functionality, etc. However, since `import.meta.resolve()` is less ambiguous and specifically designed to indicate a module path resolution dependency, you should use `import.meta.resolve(moduleName)` instead of `new URL(moduleName, import.meta.url)` for these use cases wherever possible.
### Not an ECMAScript feature
`import.meta.resolve()` is not specified or documented as part of the [ECMAScript specification](/en-US/docs/Web/JavaScript/JavaScript_technologies_overview#javascript_the_core_language_ecmascript) for JavaScript modules. Instead, the specification defines [the `import.meta` object](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#prod-ImportMeta) but [leaves all its properties as "host-defined"](https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#sec-hostgetimportmetaproperties). The WHATWG HTML standard picks up where the ECMAScript standard leaves off, and [defines `import.meta.resolve`](https://html.spec.whatwg.org/multipage/webappapis.html#hostgetimportmetaproperties) using its [module specifier resolution](https://html.spec.whatwg.org/multipage/webappapis.html#resolve-a-module-specifier).
This means that `import.meta.resolve()` is not required to be implemented by all conformant JavaScript implementations. However, `import.meta.resolve()` may also be available in non-browser environments:
- Deno implements [compatibility with browser behavior](https://deno.land/manual/runtime/import_meta_api).
- Node.js also implements [the `import.meta.resolve()` function](https://nodejs.org/docs/latest/api/esm.html#importmetaresolvespecifier), but adds an additional `parent` parameter if you use the `--experimental-import-meta-resolve` flag.
## Examples
### Resolve a path for the Worker() constructor
`import.meta.resolve()` is particularly valuable for APIs that take a path to a script file as an argument, such as the [`Worker()`](/en-US/docs/Web/API/Worker/Worker) constructor:
```js
// main.js
const workerPath = import.meta.resolve("./worker.js");
const worker = new Worker(workerPath, { type: "module" });
worker.addEventListener("message", console.log);
```
```js
// worker.js
self.postMessage("hello!");
```
This is also useful to calculate paths for other workers, such as [service workers](/en-US/docs/Web/API/ServiceWorker) and [shared workers](/en-US/docs/Web/API/SharedWorker). However, if you are using a relative path to calculate the URL of a service worker, keep in mind that the directory of the resolved path determines its [registration scope](/en-US/docs/Web/API/ServiceWorkerRegistration/scope) by default (although a different scope can be specified [during registration](/en-US/docs/Web/API/ServiceWorkerContainer/register)).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`import`](/en-US/docs/Web/JavaScript/Reference/Statements/import)
- [`import()`](/en-US/docs/Web/JavaScript/Reference/Operators/import)
- [`import.meta`](/en-US/docs/Web/JavaScript/Reference/Operators/import.meta)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/logical_or/index.md | ---
title: Logical OR (||)
slug: Web/JavaScript/Reference/Operators/Logical_OR
page-type: javascript-operator
browser-compat: javascript.operators.logical_or
---
{{jsSidebar("Operators")}}
The **logical OR (`||`)** (logical disjunction) operator for a set of operands
is true if and only if one or more of its operands is true. It is typically used with
boolean (logical) values. When it is, it returns a Boolean value. However,
the `||` operator actually returns the value of one of the specified
operands, so if this operator is used with non-Boolean values, it will return a
non-Boolean value.
{{EmbedInteractiveExample("pages/js/expressions-logical-or.html", "shorter")}}
## Syntax
```js-nolint
x || y
```
## Description
If `x` can be converted to `true`, returns
`x`; else, returns `y`.
If a value can be converted to `true`, the value is so-called
{{Glossary("truthy")}}. If a value can be converted to `false`, the value is
so-called {{Glossary("falsy")}}.
Examples of expressions that can be converted to false are:
- `null`;
- `NaN`;
- `0`;
- empty string (`""` or `''` or ` `` `);
- `undefined`.
Even though the `||` operator can be used with operands that are not Boolean
values, it can still be considered a boolean operator since its return value can always
be converted to a [boolean primitive](/en-US/docs/Web/JavaScript/Data_structures#boolean_type).
To explicitly convert its return value (or any expression in general) to the
corresponding boolean value, use a double {{jsxref("Operators/Logical_NOT", "NOT operator", "", 1)}} or the {{jsxref("Boolean/Boolean", "Boolean()")}}
constructor.
### Short-circuit evaluation
The logical OR expression is evaluated left to right, it is tested for possible
"short-circuit" evaluation using the following rule:
`(some truthy expression) || expr` is short-circuit evaluated to
the truthy expression.
Short circuit means that the `expr` part above is **not
evaluated**, hence any side effects of doing so do not take effect (e.g., if
`expr` is a function call, the calling never takes place). This
happens because the value of the operator is already determined after the evaluation of
the first operand. See example:
```js
function A() {
console.log("called A");
return false;
}
function B() {
console.log("called B");
return true;
}
console.log(B() || A());
// Logs "called B" due to the function call,
// then logs true (which is the resulting value of the operator)
```
### Operator precedence
The following expressions might seem equivalent, but they are not, because the
`&&` operator is executed before the `||` operator
(see [operator precedence](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence)).
```js-nolint
true || false && false; // returns true, because && is executed first
(true || false) && false; // returns false, because grouping has the highest precedence
```
## Examples
### Using OR
The following code shows examples of the `||` (logical OR) operator.
```js
true || true; // t || t returns true
false || true; // f || t returns true
true || false; // t || f returns true
false || 3 === 4; // f || f returns false
"Cat" || "Dog"; // t || t returns "Cat"
false || "Cat"; // f || t returns "Cat"
"Cat" || false; // t || f returns "Cat"
"" || false; // f || f returns false
false || ""; // f || f returns ""
false || varObject; // f || object returns varObject
```
> **Note:** If you use this operator to provide a default value to some
> variable, be aware that any _falsy_ value will not be used. If you only need to
> filter out [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) or {{jsxref("undefined")}}, consider using
> [the nullish coalescing operator](/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing).
### Conversion rules for booleans
#### Converting AND to OR
The following operation involving **booleans**:
```js-nolint
bCondition1 && bCondition2
```
is always equal to:
```js-nolint
!(!bCondition1 || !bCondition2)
```
#### Converting OR to AND
The following operation involving **booleans**:
```js-nolint
bCondition1 || bCondition2
```
is always equal to:
```js-nolint
!(!bCondition1 && !bCondition2)
```
### Removing nested parentheses
As logical expressions are evaluated left to right, it is always possible to remove
parentheses from a complex expression following some rules.
The following composite operation involving **booleans**:
```js-nolint
bCondition1 && (bCondition2 || bCondition3)
```
is always equal to:
```js-nolint
!(!bCondition1 || !bCondition2 && !bCondition3)
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Nullish coalescing operator (`??`)](/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing)
- {{jsxref("Boolean")}}
- {{Glossary("Truthy")}}
- {{Glossary("Falsy")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/typeof/index.md | ---
title: typeof
slug: Web/JavaScript/Reference/Operators/typeof
page-type: javascript-operator
browser-compat: javascript.operators.typeof
---
{{jsSidebar("Operators")}}
The **`typeof`** operator returns a string indicating the type of the operand's value.
{{EmbedInteractiveExample("pages/js/expressions-typeof.html")}}
## Syntax
```js-nolint
typeof operand
```
### Parameters
- `operand`
- : An expression representing the object or [primitive](/en-US/docs/Glossary/Primitive) whose type is to be returned.
## Description
The following table summarizes the possible return values of `typeof`. For more information about types and primitives, see also the [JavaScript data structure](/en-US/docs/Web/JavaScript/Data_structures) page.
| Type | Result |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- |
| [Undefined](/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) | `"undefined"` |
| [Null](/en-US/docs/Web/JavaScript/Reference/Operators/null) | `"object"` ([reason](#typeof_null)) |
| [Boolean](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean) | `"boolean"` |
| [Number](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number) | `"number"` |
| [BigInt](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | `"bigint"` |
| [String](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) | `"string"` |
| [Symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) | `"symbol"` |
| [Function](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) (implements [[Call]] in ECMA-262 terms; [classes](/en-US/docs/Web/JavaScript/Reference/Statements/class) are functions as well) | `"function"` |
| Any other object | `"object"` |
This list of values is exhaustive. No spec-compliant engines are reported to produce (or had historically produced) values other than those listed.
## Examples
### Basic usage
```js
// Numbers
typeof 37 === "number";
typeof 3.14 === "number";
typeof 42 === "number";
typeof Math.LN2 === "number";
typeof Infinity === "number";
typeof NaN === "number"; // Despite being "Not-A-Number"
typeof Number("1") === "number"; // Number tries to parse things into numbers
typeof Number("shoe") === "number"; // including values that cannot be type coerced to a number
typeof 42n === "bigint";
// Strings
typeof "" === "string";
typeof "bla" === "string";
typeof `template literal` === "string";
typeof "1" === "string"; // note that a number within a string is still typeof string
typeof typeof 1 === "string"; // typeof always returns a string
typeof String(1) === "string"; // String converts anything into a string, safer than toString
// Booleans
typeof true === "boolean";
typeof false === "boolean";
typeof Boolean(1) === "boolean"; // Boolean() will convert values based on if they're truthy or falsy
typeof !!1 === "boolean"; // two calls of the ! (logical NOT) operator are equivalent to Boolean()
// Symbols
typeof Symbol() === "symbol";
typeof Symbol("foo") === "symbol";
typeof Symbol.iterator === "symbol";
// Undefined
typeof undefined === "undefined";
typeof declaredButUndefinedVariable === "undefined";
typeof undeclaredVariable === "undefined";
// Objects
typeof { a: 1 } === "object";
// use Array.isArray or Object.prototype.toString.call
// to differentiate regular objects from arrays
typeof [1, 2, 4] === "object";
typeof new Date() === "object";
typeof /regex/ === "object";
// The following are confusing, dangerous, and wasteful. Avoid them.
typeof new Boolean(true) === "object";
typeof new Number(1) === "object";
typeof new String("abc") === "object";
// Functions
typeof function () {} === "function";
typeof class C {} === "function";
typeof Math.sin === "function";
```
### typeof null
```js
// This stands since the beginning of JavaScript
typeof null === "object";
```
In the first implementation of JavaScript, JavaScript values were represented as a type tag and a value. The type tag for objects was `0`. `null` was represented as the NULL pointer (`0x00` in most platforms). Consequently, `null` had `0` as type tag, hence the `typeof` return value `"object"`. ([reference](https://2ality.com/2013/10/typeof-null.html))
A fix was proposed for ECMAScript (via an opt-in), but [was rejected](https://web.archive.org/web/20160331031419/http://wiki.ecmascript.org:80/doku.php?id=harmony:typeof_null). It would have resulted in `typeof null === "null"`.
### Using new operator
All constructor functions called with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new) will return non-primitives (`"object"` or `"function"`). Most return objects, with the notable exception being [`Function`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function), which returns a function.
```js
const str = new String("String");
const num = new Number(100);
typeof str; // "object"
typeof num; // "object"
const func = new Function();
typeof func; // "function"
```
### Need for parentheses in syntax
The `typeof` operator has higher [precedence](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence) than binary operators like addition (`+`). Therefore, parentheses are needed to evaluate the type of an addition result.
```js
// Parentheses can be used for determining the data type of expressions.
const someData = 99;
typeof someData + " Wisen"; // "number Wisen"
typeof (someData + " Wisen"); // "string"
```
### Interaction with undeclared and uninitialized variables
`typeof` is generally always guaranteed to return a string for any operand it is supplied with. Even with undeclared identifiers, `typeof` will return `"undefined"` instead of throwing an error.
```js
typeof undeclaredVariable; // "undefined"
```
However, using `typeof` on lexical declarations ({{jsxref("Statements/let", "let")}} {{jsxref("Statements/const", "const")}}, and [`class`](/en-US/docs/Web/JavaScript/Reference/Statements/class)) in the same block before the place of declaration will throw a {{jsxref("ReferenceError")}}. Block scoped variables are in a _[temporal dead zone](/en-US/docs/Web/JavaScript/Reference/Statements/let#temporal_dead_zone_tdz)_ from the start of the block until the initialization is processed, during which it will throw an error if accessed.
```js example-bad
typeof newLetVariable; // ReferenceError
typeof newConstVariable; // ReferenceError
typeof newClass; // ReferenceError
let newLetVariable;
const newConstVariable = "hello";
class newClass {}
```
### Exceptional behavior of document.all
All current browsers expose a non-standard host object [`document.all`](/en-US/docs/Web/API/Document/all) with type `undefined`.
```js
typeof document.all === "undefined";
```
Although `document.all` is also [falsy](/en-US/docs/Glossary/Falsy) and [loosely equal](/en-US/docs/Web/JavaScript/Reference/Operators/Equality) to `undefined`, it is not [`undefined`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined). The case of `document.all` having type `"undefined"` is classified in the web standards as a "willful violation" of the original ECMAScript standard for web compatibility.
### Custom method that gets a more specific type
`typeof` is very useful, but it's not as versatile as might be required. For example, `typeof []` is `"object"`, as well as `typeof new Date()`, `typeof /abc/`, etc.
For greater specificity in checking types, here we present a custom `type(value)` function, which mostly mimics the behavior of `typeof`, but for non-primitives (i.e. objects and functions), it returns a more granular type name where possible.
```js
function type(value) {
if (value === null) {
return "null";
}
const baseType = typeof value;
// Primitive types
if (!["object", "function"].includes(baseType)) {
return baseType;
}
// Symbol.toStringTag often specifies the "display name" of the
// object's class. It's used in Object.prototype.toString().
const tag = value[Symbol.toStringTag];
if (typeof tag === "string") {
return tag;
}
// If it's a function whose source code starts with the "class" keyword
if (
baseType === "function" &&
Function.prototype.toString.call(value).startsWith("class")
) {
return "class";
}
// The name of the constructor; for example `Array`, `GeneratorFunction`,
// `Number`, `String`, `Boolean` or `MyCustomClass`
const className = value.constructor.name;
if (typeof className === "string" && className !== "") {
return className;
}
// At this point there's no robust way to get the type of value,
// so we use the base implementation.
return baseType;
}
```
For checking potentially non-existent variables that would otherwise throw a {{jsxref("ReferenceError")}}, use `typeof nonExistentVar === "undefined"` because this behavior cannot be mimicked with custom code.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Operators/instanceof", "instanceof")}}
- [`document.all` willful violation of the standard](https://github.com/tc39/ecma262/issues/668)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/logical_not/index.md | ---
title: Logical NOT (!)
slug: Web/JavaScript/Reference/Operators/Logical_NOT
page-type: javascript-operator
browser-compat: javascript.operators.logical_not
---
{{jsSidebar("Operators")}}
The **logical NOT (`!`)** (logical complement, negation) operator takes truth to
falsity and vice versa. It is typically used with boolean (logical)
values. When used with non-Boolean values, it returns `false` if its single
operand can be converted to `true`; otherwise, returns `true`.
{{EmbedInteractiveExample("pages/js/expressions-logical-not.html", "shorter")}}
## Syntax
```js-nolint
!x
```
## Description
Returns `false` if its single operand can be converted to `true`;
otherwise, returns `true`.
If a value can be converted to `true`, the value is so-called
{{Glossary("truthy")}}. If a value can be converted to `false`, the value is
so-called {{Glossary("falsy")}}.
Examples of expressions that can be converted to false are:
- `null`;
- `NaN`;
- `0`;
- empty string (`""` or `''` or ` `` `);
- `undefined`.
Even though the `!` operator can be used with operands that are not Boolean values, it can still be considered a boolean operator since its return value can always be converted to a [boolean primitive](/en-US/docs/Web/JavaScript/Data_structures#boolean_type). To explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double NOT operator (`!!`) or the {{jsxref("Boolean/Boolean", "Boolean")}} constructor.
## Examples
### Using NOT
The following code shows examples of the `!` (logical NOT) operator.
```js
!true; // !t returns false
!false; // !f returns true
!""; // !f returns true
!"Cat"; // !t returns false
```
### Double NOT (`!!`)
It is possible to use a couple of NOT operators in series to explicitly force the
conversion of any value to the corresponding [boolean primitive](/en-US/docs/Web/JavaScript/Data_structures#boolean_type).
The conversion is based on the "truthyness" or "falsyness" of the value (see
{{Glossary("truthy")}} and {{Glossary("falsy")}}).
The same conversion can be done through the {{jsxref("Boolean/Boolean", "Boolean()")}} function.
```js
!!true; // !!truthy returns true
!!{}; // !!truthy returns true: any object is truthy...
!!new Boolean(false); // ...even Boolean objects with a false .valueOf()!
!!false; // !!falsy returns false
!!""; // !!falsy returns false
!!Boolean(false); // !!falsy returns false
```
### Converting between NOTs
The following operation involving **booleans**:
```js-nolint
!!bCondition
```
is always equal to:
```js-nolint
bCondition
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Boolean")}}
- {{Glossary("Truthy")}}
- {{Glossary("Falsy")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/logical_and_assignment/index.md | ---
title: Logical AND assignment (&&=)
slug: Web/JavaScript/Reference/Operators/Logical_AND_assignment
page-type: javascript-operator
browser-compat: javascript.operators.logical_and_assignment
---
{{jsSidebar("Operators")}}
The **logical AND assignment (`&&=`)** operator only evaluates the right operand and assigns to the left if the left operand is {{Glossary("truthy")}}.
{{EmbedInteractiveExample("pages/js/expressions-logical-and-assignment.html")}}
## Syntax
```js-nolint
x &&= y
```
## Description
Logical AND assignment [_short-circuits_](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence#short-circuiting), meaning that `x &&= y` is equivalent to `x && (x = y)`, except that the expression `x` is only evaluated once.
No assignment is performed if the left-hand side is not truthy, due to short-circuiting of the [logical AND](/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND) operator. For example, the following does not throw an error, despite `x` being `const`:
```js
const x = 0;
x &&= 2;
```
Neither would the following trigger the setter:
```js
const x = {
get value() {
return 0;
},
set value(v) {
console.log("Setter called");
},
};
x.value &&= 2;
```
In fact, if `x` is not truthy, `y` is not evaluated at all.
```js
const x = 0;
x &&= console.log("y evaluated");
// Logs nothing
```
## Examples
### Using logical AND assignment
```js
let x = 0;
let y = 1;
x &&= 0; // 0
x &&= 1; // 0
y &&= 1; // 1
y &&= 0; // 0
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Logical AND (`&&`)](/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND)
- [Nullish coalescing operator (`??`)](/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing)
- [Bitwise AND assignment (`&=`)](/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND_assignment)
- {{Glossary("Truthy")}}
- {{Glossary("Falsy")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/in/index.md | ---
title: in
slug: Web/JavaScript/Reference/Operators/in
page-type: javascript-operator
browser-compat: javascript.operators.in
---
{{jsSidebar("Operators")}}
The **`in`** operator returns `true` if the specified property is in the specified object or its prototype chain.
The `in` operator cannot be used to search for values in other collections. To test if a certain value exists in an array, use {{jsxref("Array.prototype.includes()")}}. For sets, use {{jsxref("Set.prototype.has()")}}.
{{EmbedInteractiveExample("pages/js/expressions-inoperator.html")}}
## Syntax
```js-nolint
prop in object
#prop in object
```
### Parameters
- `prop`
- : A string or symbol representing a property name (non-symbols will be [coerced to strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion)). Can also be a [private property identifier](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties).
- `object`
- : Object to check if it (or its prototype chain) contains the property with specified name (`prop`).
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if `object` is not an object (i.e. a primitive).
## Description
The `in` operator tests if a string or symbol property is present in an object or its prototype chain. If you want to check for only _non-inherited_ properties, use {{jsxref("Object.hasOwn()")}} instead.
A property may be present in an object but have value `undefined`. Therefore, `x in obj` is not the same as `obj.x !== undefined`. To make `in` return `false` after a property is added, use the [`delete`](/en-US/docs/Web/JavaScript/Reference/Operators/delete) operator instead of setting that property's value to `undefined`.
You can also use the `in` operator to check whether a particular [private class field or method](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties) has been defined in an object. The operator returns `true` if the property is defined, and `false` otherwise. This is known as a _branded check_, because it returns `true` if and only if the object was created with that class constructor, after which you can safely access other private properties as well.
This is a special syntax β the left-hand side of the `in` operator is a property identifier instead of an expression, but unquoted (because otherwise it's a string property, not a private property).
Because accessing private properties on objects unrelated to the current class throws a {{jsxref("TypeError")}} instead of returning `undefined`, this syntax allows you to shorten:
```js
class C {
#x;
static isC(obj) {
try {
obj.#x;
return true;
} catch {
return false;
}
}
}
```
To:
```js
class C {
#x;
static isC(obj) {
return #x in obj;
}
}
```
It also generally avoids the need for dealing with error handling just to access a private property that may be nonexistent.
However, the `in` operator still requires the private property to be declared beforehand in the enclosing class β otherwise, it would throw a {{jsxref("SyntaxError")}} ("Private field '#x' must be declared in an enclosing class"), the same one as when you try to access an undeclared private property.
```js-nolint example-bad
class C {
foo() {
#x in this;
}
}
new C().foo(); // SyntaxError: Private field '#x' must be declared in an enclosing class
```
## Examples
### Basic usage
The following examples show some uses of the `in` operator.
```js
// Arrays
const trees = ["redwood", "bay", "cedar", "oak", "maple"];
0 in trees; // returns true
3 in trees; // returns true
6 in trees; // returns false
"bay" in trees; // returns false (you must specify the index number, not the value at that index)
"length" in trees; // returns true (length is an Array property)
Symbol.iterator in trees; // returns true
// Predefined objects
"PI" in Math; // returns true
// Custom objects
const mycar = { make: "Honda", model: "Accord", year: 1998 };
"make" in mycar; // returns true
"model" in mycar; // returns true
```
You must specify an object on the right side of the `in` operator. For example, you can specify a string created with the `String` constructor, but you cannot specify a string literal.
```js
const color1 = new String("green");
"length" in color1; // returns true
const color2 = "coral";
// generates an error (color2 is not a String object)
"length" in color2;
```
### Using the in operator with deleted or undefined properties
If you delete a property with the [`delete`](/en-US/docs/Web/JavaScript/Reference/Operators/delete) operator, the `in` operator returns `false` for that property.
```js
const mycar = { make: "Honda", model: "Accord", year: 1998 };
delete mycar.make;
"make" in mycar; // returns false
const trees = ["redwood", "bay", "cedar", "oak", "maple"];
delete trees[3];
3 in trees; // returns false
```
If you set a property to {{jsxref("undefined")}} but do not delete it, the `in` operator returns true for that property.
```js
const mycar = { make: "Honda", model: "Accord", year: 1998 };
mycar.make = undefined;
"make" in mycar; // returns true
```
```js
const trees = ["redwood", "bay", "cedar", "oak", "maple"];
trees[3] = undefined;
3 in trees; // returns true
```
The `in` operator will return `false` for [empty array slots](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), even if accessing it directly returns `undefined`.
```js
const empties = new Array(3);
empties[2]; // returns undefined
2 in empties; // returns false
```
To avoid this, make sure a new array is always filled with non-empty values or not write to indexes past the end of array.
```js
const empties = new Array(3).fill(undefined);
2 in empties; // returns true
```
### Inherited properties
The `in` operator returns `true` for properties in the prototype chain. This may be undesirable if you are using objects to store arbitrary key-value pairs.
```js example-bad
const ages = { alice: 18, bob: 27 };
function hasPerson(name) {
return name in ages;
}
hasPerson("hasOwnProperty"); // true
```
You can use {{jsxref("Object.hasOwn()")}} to check if the object has the key.
```js
const ages = { alice: 18, bob: 27 };
function hasPerson(name) {
return Object.hasOwn(ages, name);
}
hasPerson("hasOwnProperty"); // false
```
Alternatively, you should consider using a [null prototype object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) or a {{jsxref("Map")}} for storing `ages`, to avoid other bugs.
```js example-good
const ages = new Map([
["alice", 18],
["bob", 27],
]);
function hasPerson(name) {
return ages.has(name);
}
hasPerson("hasOwnProperty"); // false
```
### Using the in operator to implement branded checks
The code fragment below demonstrates a static function that tells if an object was created with the `Person` constructor and therefore can perform other methods safely.
```js
class Person {
#age;
constructor(age) {
this.#age = age;
}
static isPerson(o) {
return #age in o;
}
ageDifference(other) {
return this.#age - other.#age;
}
}
const p1 = new Person(20);
const p2 = new Person(30);
console.log(p1.ageDifference(p2)); // -10
console.log(Person.isPerson(p1)); // true
if (Person.isPerson(p1) && Person.isPerson(p2)) {
console.log(p1.ageDifference(p2)); // -10
}
```
It helps to prevent the following case:
```js
const p2 = {};
p1.ageDifference(p2); // TypeError: Cannot read private member #age from an object whose class did not declare it
```
Without the `in` operator, you would have to use a `try...catch` block to check if the object has the private property.
You can also implement this as a [`@@hasInstance`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance) method of the class, so that you can use the [`instanceof`](/en-US/docs/Web/JavaScript/Reference/Operators/instanceof) operator to perform the same check (which, by default, only checks for the existence of `Person.prototype` in the object's prototype chain).
```js
class Person {
#age;
constructor(age) {
this.#age = age;
}
static [Symbol.hasInstance](o) {
// Testing `this` to prevent false-positives when
// calling `instanceof SubclassOfPerson`
return this === Person && #age in o;
}
ageDifference(other) {
return this.#age - other.#age;
}
}
const p1 = new Person(20);
const p2 = new Person(30);
if (p1 instanceof Person && p2 instanceof Person) {
console.log(p1.ageDifference(p2)); // -10
}
```
For more examples, see [Private properties](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties) and the [class guide](/en-US/docs/Web/JavaScript/Guide/Using_classes#private_fields).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in)
- [`delete`](/en-US/docs/Web/JavaScript/Reference/Operators/delete)
- {{jsxref("Object.hasOwn()")}}
- {{jsxref("Reflect.has()")}}
- [Enumerability and ownership of properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/operators | data/mdn-content/files/en-us/web/javascript/reference/operators/less_than/index.md | ---
title: Less than (<)
slug: Web/JavaScript/Reference/Operators/Less_than
page-type: javascript-operator
browser-compat: javascript.operators.less_than
---
{{jsSidebar("Operators")}}
The **less than (`<`)** operator returns `true` if the left operand is less than the right operand, and `false` otherwise.
{{EmbedInteractiveExample("pages/js/expressions-less-than.html")}}
## Syntax
```js-nolint
x < y
```
## Description
The operands are compared with multiple rounds of coercion, which can be summarized as follows:
- First, objects are [converted to primitives](/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion) by calling its [`[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive) (with `"number"` as hint), [`valueOf()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf), and [`toString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString) methods, in that order. The left operand is always coerced before the right one. Note that although `[@@toPrimitive]()` is called with the `"number"` hint (meaning there's a slight preference for the object to become a number), the return value is not [converted to a number](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion), since strings are still specially handled.
- If both values are strings, they are compared as strings, based on the values of the UTF-16 code units (not Unicode code points) they contain.
- Otherwise JavaScript attempts to convert non-numeric types to numeric values:
- Boolean values `true` and `false` are converted to 1 and 0 respectively.
- `null` is converted to 0.
- `undefined` is converted to `NaN`.
- Strings are converted based on the values they contain, and are converted as `NaN` if they do not contain numeric values.
- If either value is [`NaN`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN), the operator returns `false`.
- Otherwise the values are compared as numeric values. BigInt and number values can be compared together.
Other operators, including [`>`](/en-US/docs/Web/JavaScript/Reference/Operators/Greater_than), [`>=`](/en-US/docs/Web/JavaScript/Reference/Operators/Greater_than_or_equal), and [`<=`](/en-US/docs/Web/JavaScript/Reference/Operators/Less_than_or_equal), use the same algorithm as `<`. There are two cases where all four operators return `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`.)
For all other cases, the four operators have the following relationships:
```js
x < y === !(x >= y);
x <= y === !(x > y);
x > y === y < x;
x >= y === y <= x;
```
> **Note:** One observable difference between `<` and `>` is the order of coercion, especially if the coercion to primitive has side effects. All comparison operators coerce the left operand before the right operand.
## Examples
### String to string comparison
```js
"a" < "b"; // true
"a" < "a"; // false
"a" < "3"; // false
"\uD855\uDE51" < "\uFF3A"; // true
```
### String to number comparison
```js
"5" < 3; // false
"3" < 3; // false
"3" < 5; // true
"hello" < 5; // false
5 < "hello"; // false
"5" < 3n; // false
"3" < 5n; // true
```
### Number to Number comparison
```js
5 < 3; // false
3 < 3; // false
3 < 5; // true
```
### Number to BigInt comparison
```js
5n < 3; // false
3 < 5n; // true
```
### Comparing Boolean, null, undefined, NaN
```js
true < false; // false
false < true; // true
0 < true; // true
true < 1; // false
null < 0; // false
null < 1; // true
undefined < 3; // false
3 < undefined; // false
3 < NaN; // false
NaN < 3; // false
```
### Comparison with side effects
Comparisons always coerce their operands to primitives. This means the same object may end up having different values within one comparison expression. For example, you may have two values that are both greater than and less than the other.
```js
class Mystery {
static #coercionCount = -1;
valueOf() {
Mystery.#coercionCount++;
// The left operand is coerced first, so this will return 0
// Then it returns 1 for the right operand
return Mystery.#coercionCount % 2;
}
}
const l = new Mystery();
const r = new Mystery();
console.log(l < r && r < l);
// true
```
> **Warning:** This can be a source of confusion. If your objects provide custom primitive conversion logic, make sure it is _idempotent_: multiple coercions should return the same value.
## 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 or equal (`<=`)](/en-US/docs/Web/JavaScript/Reference/Operators/Less_than_or_equal)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference | data/mdn-content/files/en-us/web/javascript/reference/functions/index.md | ---
title: Functions
slug: Web/JavaScript/Reference/Functions
page-type: guide
browser-compat: javascript.functions
---
{{jsSidebar("Functions")}}
Generally speaking, a function is a "subprogram" that can be _called_ by code external (or internal, in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the _function body_. Values can be _passed_ to a function as parameters, and the function will _return_ a value.
In JavaScript, functions are [first-class objects](/en-US/docs/Glossary/First-class_Function), because they can be passed to other functions, returned from functions, and assigned to variables and properties. They can also have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called.
For more examples and explanations, see the [JavaScript guide about functions](/en-US/docs/Web/JavaScript/Guide/Functions).
## Description
Function values are typically instances of [`Function`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function). See {{jsxref("Function")}} for information on properties and methods of `Function` objects. Callable values cause [`typeof`](/en-US/docs/Web/JavaScript/Reference/Operators/typeof) to return `"function"` instead of `"object"`.
> **Note:** Not all callable values are `instanceof Function`. For example, the `Function.prototype` object is callable but not an instance of `Function`. You can also manually set the [prototype chain](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain) of your function so it no longer inherits from `Function.prototype`. However, such cases are extremely rare.
### Return value
By default, if a function's execution doesn't end at a [`return`](/en-US/docs/Web/JavaScript/Reference/Statements/return) statement, or if the `return` keyword doesn't have an expression after it, then the return value is {{jsxref("undefined")}}. The `return` statement allows you to return an arbitrary value from the function. One function call can only return one value, but you can simulate the effect of returning multiple values by returning an object or array and [destructuring](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) the result.
> **Note:** Constructors called with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new) have a different set of logic to determine their return values.
### Passing arguments
[Parameters and arguments](<https://en.wikipedia.org/wiki/Parameter_(computer_programming)#Parameters_and_arguments>) have slightly different meanings, but in MDN web docs, we often use them interchangeably. For a quick reference:
```js
function formatNumber(num) {
return num.toFixed(2);
}
formatNumber(2);
```
In this example, the `num` variable is called the function's _parameter_: it's declared in the parenthesis-enclosed list of the function's definition. The function expects the `num` parameter to be a number β although this is not enforceable in JavaScript without writing runtime validation code. In the `formatNumber(2)` call, the number `2` is the function's _argument_: it's the value that is actually passed to the function in the function call. The argument value can be accessed inside the function body through the corresponding parameter name or the [`arguments`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments) object.
Arguments are always [_passed by value_](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_reference) and never _passed by reference_. This means that if a function reassigns a parameter, the value won't change outside the function. More precisely, object arguments are [_passed by sharing_](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing), which means if the object's properties are mutated, the change will impact the outside of the function. For example:
```js
function updateBrand(obj) {
// Mutating the object is visible outside the function
obj.brand = "Toyota";
// Try to reassign the parameter, but this won't affect
// the variable's value outside the function
obj = null;
}
const car = {
brand: "Honda",
model: "Accord",
year: 1998,
};
console.log(car.brand); // Honda
// Pass object reference to the function
updateBrand(car);
// updateBrand mutates car
console.log(car.brand); // Toyota
```
The [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this) keyword refers to the object that the function is accessed on β it does not refer to the currently executing function, so you must refer to the function value by name, even within the function body.
### Defining functions
Broadly speaking, JavaScript has four kinds of functions:
- Regular function: can return anything; always runs to completion after invocation
- Generator function: returns a [`Generator`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator) object; can be paused and resumed with the [`yield`](/en-US/docs/Web/JavaScript/Reference/Operators/yield) operator
- Async function: returns a [`Promise`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise); can be paused and resumed with the [`await`](/en-US/docs/Web/JavaScript/Reference/Operators/await) operator
- Async generator function: returns an [`AsyncGenerator`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator) object; both the `await` and `yield` operators can be used
For every kind of function, there are three ways to define it:
- Declaration
- : [`function`](/en-US/docs/Web/JavaScript/Reference/Statements/function), [`function*`](/en-US/docs/Web/JavaScript/Reference/Statements/function*), [`async function`](/en-US/docs/Web/JavaScript/Reference/Statements/async_function), [`async function*`](/en-US/docs/Web/JavaScript/Reference/Statements/async_function*)
- Expression
- : [`function`](/en-US/docs/Web/JavaScript/Reference/Operators/function), [`function*`](/en-US/docs/Web/JavaScript/Reference/Operators/function*), [`async function`](/en-US/docs/Web/JavaScript/Reference/Operators/async_function), [`async function*`](/en-US/docs/Web/JavaScript/Reference/Operators/async_function*)
- Constructor
- : [`Function()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function), [`GeneratorFunction()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/GeneratorFunction/GeneratorFunction), [`AsyncFunction()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction/AsyncFunction), [`AsyncGeneratorFunction()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGeneratorFunction/AsyncGeneratorFunction)
In addition, there are special syntaxes for defining [arrow functions](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) and [methods](/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions), which provide more precise semantics for their usage. [Classes](/en-US/docs/Web/JavaScript/Reference/Classes) are conceptually not functions (because they throw an error when called without `new`), but they also inherit from `Function.prototype` and have `typeof MyClass === "function"`.
```js
// Constructor
const multiply = new Function("x", "y", "return x * y");
// Declaration
function multiply(x, y) {
return x * y;
} // No need for semicolon here
// Expression; the function is anonymous but assigned to a variable
const multiply = function (x, y) {
return x * y;
};
// Expression; the function has its own name
const multiply = function funcName(x, y) {
return x * y;
};
// Arrow function
const multiply = (x, y) => x * y;
// Method
const obj = {
multiply(x, y) {
return x * y;
},
};
```
All syntaxes do approximately the same thing, but there are some subtle behavior differences.
- The `Function()` constructor, `function` expression, and `function` declaration syntaxes create full-fledged function objects, which can be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). However, arrow functions and methods cannot be constructed. Async functions, generator functions, and async generator functions are not constructible regardless of syntax.
- The `function` declaration creates functions that are [_hoisted_](/en-US/docs/Web/JavaScript/Guide/Functions#function_hoisting). Other syntaxes do not hoist the function and the function value is only visible after the definition.
- The arrow function and `Function()` constructor always create _anonymous_ functions, which means they can't easily call themselves recursively. One way to call an arrow function recursively is by assigning it to a variable.
- The arrow function syntax does not have access to `arguments` or `this`.
- The `Function()` constructor cannot access any local variables β it only has access to the global scope.
- The `Function()` constructor causes runtime compilation and is often slower than other syntaxes.
For `function` expressions, there is a distinction between the function name and the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned. The function name can be different from the variable the function is assigned to β they have no relation to each other. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or gets another value, if the same name is declared elsewhere). For example:
```js
const y = function x() {};
console.log(x); // ReferenceError: x is not defined
```
On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope in which the function is declared.
A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in, as well as in their own body.
A function defined by `new Function` will dynamically have its source assembled, which is observable when you serialize it. For example, `console.log(new Function().toString())` gives:
```js-nolint
function anonymous(
) {
}
```
This is the actual source used to compile the function. However, although the `Function()` constructor will create the function with name `anonymous`, this name is not added to the scope of the body. The body only ever has access to global variables. For example, the following would result in an error:
```js
new Function("alert(anonymous);")();
```
A function defined by a function expression or by a function declaration inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a `Function` constructor does not inherit any scope other than the global scope (which all functions inherit).
```js
// p is a global variable
globalThis.p = 5;
function myFunc() {
// p is a local variable
const p = 9;
function decl() {
console.log(p);
}
const expr = function () {
console.log(p);
};
const cons = new Function("\tconsole.log(p);");
decl();
expr();
cons();
}
myFunc();
// Logs:
// 9 (for 'decl' by function declaration (current scope))
// 9 (for 'expr' by function expression (current scope))
// 5 (for 'cons' by Function constructor (global scope))
```
Functions defined by function expressions and function declarations are parsed only once, while a function defined by the `Function` constructor parses the string passed to it each and every time the constructor is called. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than `new Function(...)`. Therefore the `Function` constructor should generally be avoided whenever possible.
A function declaration may be unintentionally turned into a function expression when it appears in an expression context.
```js
// A function declaration
function foo() {
console.log("FOO!");
}
doSomething(
// A function expression passed as an argument
function foo() {
console.log("FOO!");
},
);
```
On the other hand, a function expression may also be turned into a function declaration. An [expression statement](/en-US/docs/Web/JavaScript/Reference/Statements/Expression_statement) cannot begin with the `function` or `async function` keywords, which is a common mistake when implementing [IIFEs](/en-US/docs/Glossary/IIFE) (Immediately Invoked Function Expressions).
```js-nolint example-bad
function () { // SyntaxError: Function statements require a function name
console.log("FOO!");
}();
function foo() {
console.log("FOO!");
}(); // SyntaxError: Unexpected token ')'
```
Instead, start the expression statement with something else, so that the `function` keyword unambiguously starts a function expression. Common options include [grouping](/en-US/docs/Web/JavaScript/Reference/Operators/Grouping) and using [`void`](/en-US/docs/Web/JavaScript/Reference/Operators/void).
```js-nolint example-good
(function () {
console.log("FOO!");
})();
void function () {
console.log("FOO!");
}();
```
### Function parameters
Each function parameter is a simple identifier that you can access in the local scope.
```js
function myFunc(a, b, c) {
// You can access the values of a, b, and c here
}
```
There are three special parameter syntaxes:
- [_Default parameters_](/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters) allow formal parameters to be initialized with default values if no value or `undefined` is passed.
- The [_rest parameter_](/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters) allows representing an indefinite number of arguments as an array.
- [_Destructuring_](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) allows unpacking elements from arrays, or properties from objects, into distinct variables.
```js
function myFunc({ a, b }, c = 1, ...rest) {
// You can access the values of a, b, c, and rest here
}
```
There are some consequences if one of the above non-simple parameter syntaxes is used:
- You cannot apply `"use strict"` to the function body β this causes a [syntax error](/en-US/docs/Web/JavaScript/Reference/Errors/Strict_non_simple_params).
- Even if the function is not in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode), the [`arguments`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments) object stops syncing with the named parameters, and [`arguments.callee`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee) throws an error when accessed.
### The arguments object
You can refer to a function's arguments within the function by using the [`arguments`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments) object.
- [`arguments`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments)
- : An array-like object containing the arguments passed to the currently executing function.
- [`arguments.callee`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee)
- : The currently executing function.
- [`arguments.length`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments/length)
- : The number of arguments passed to the function.
### Getter and setter functions
You can define accessor properties on any standard built-in object or user-defined object that supports the addition of new properties. Within [object literals](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) and [classes](/en-US/docs/Web/JavaScript/Reference/Classes), you can use special syntaxes to define the getter and setter of an accessor property.
- [get](/en-US/docs/Web/JavaScript/Reference/Functions/get)
- : Binds an object property to a function that will be called when that property is looked up.
- [set](/en-US/docs/Web/JavaScript/Reference/Functions/set)
- : Binds an object property to a function to be called when there is an attempt to set that property.
Note that these syntaxes create an _object property_, not a _method_. The getter and setter functions themselves can only be accessed using reflective APIs such as {{jsxref("Object.getOwnPropertyDescriptor()")}}.
### Block-level functions
In [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode), functions inside blocks are scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.
```js
"use strict";
function f() {
return 1;
}
{
function f() {
return 2;
}
}
f() === 1; // true
// f() === 2 in non-strict mode
```
### Block-level functions in non-strict code
In a word: **Don't.**
In non-strict code, function declarations inside blocks behave strangely. For example:
```js
if (shouldDefineZero) {
function zero() {
// DANGER: compatibility risk
console.log("This is zero.");
}
}
```
The semantics of this in strict mode are well-specified β `zero` only ever exists within that scope of the `if` block. If `shouldDefineZero` is false, then `zero` should never be defined, since the block never executes. However, historically, this was left unspecified, so different browsers implemented it differently in non-strict mode. For more information, see the [`function` declaration](/en-US/docs/Web/JavaScript/Reference/Statements/function#block-level_function_declaration) reference.
A safer way to define functions conditionally is to assign a function expression to a variable:
```js
// Using a var makes it available as a global variable,
// with closer behavior to a top-level function declaration
var zero;
if (shouldDefineZero) {
zero = function () {
console.log("This is zero.");
};
}
```
## Examples
### Returning a formatted number
The following function returns a string containing the formatted representation of a number padded with leading zeros.
```js
// This function returns a string padded with leading zeros
function padZeros(num, totalLen) {
let numStr = num.toString(); // Initialize return value as string
const numZeros = totalLen - numStr.length; // Calculate no. of zeros
for (let i = 1; i <= numZeros; i++) {
numStr = `0${numStr}`;
}
return numStr;
}
```
The following statements call the `padZeros` function.
```js
let result;
result = padZeros(42, 4); // returns "0042"
result = padZeros(42, 2); // returns "42"
result = padZeros(5, 4); // returns "0005"
```
### Determining whether a function exists
You can determine whether a function exists by using the [`typeof`](/en-US/docs/Web/JavaScript/Reference/Operators/typeof) operator. In the following example, a test is performed to determine if the `window` object has a property called `noFunc` that is a function. If so, it is used; otherwise, some other action is taken.
```js
if (typeof window.noFunc === "function") {
// use noFunc()
} else {
// do something else
}
```
Note that in the `if` test, a reference to `noFunc` is used β there are no parentheses `()` after the function name so the actual function is not called.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Functions](/en-US/docs/Web/JavaScript/Guide/Functions) guide
- [Classes](/en-US/docs/Web/JavaScript/Reference/Classes)
- {{jsxref("Statements/function", "function")}}
- [`function` expression](/en-US/docs/Web/JavaScript/Reference/Operators/function)
- {{jsxref("Function")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/functions | data/mdn-content/files/en-us/web/javascript/reference/functions/get/index.md | ---
title: get
slug: Web/JavaScript/Reference/Functions/get
page-type: javascript-language-feature
browser-compat: javascript.functions.get
---
{{jsSidebar("Functions")}}
The **`get`** syntax binds an object property to a function that will be called when that property is looked up. It can also be used in [classes](/en-US/docs/Web/JavaScript/Reference/Classes).
{{EmbedInteractiveExample("pages/js/functions-getter.html")}}
## Syntax
```js-nolint
{ get prop() { /* β¦ */ } }
{ get [expression]() { /* β¦ */ } }
```
There are some additional syntax restrictions:
- A getter must have exactly zero parameters.
### Parameters
- `prop`
- : The name of the property to bind to the given function. In the same way as other properties in [object initializers](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer), it can be a string literal, a number literal, or an identifier.
- `expression`
- : You can also use expressions for a computed property name to bind to the given function.
## Description
Sometimes it is desirable to allow access to a property that returns a dynamically computed value, or you may want to reflect the status of an internal variable without requiring the use of explicit method calls. In JavaScript, this can be accomplished with the use of a _getter_.
An object property is either a data property or an accessor property, but it cannot simultaneously be both. Read {{jsxref("Object.defineProperty()")}} for more information. The getter syntax allows you to specify the getter function in an object initializer.
```js
const obj = {
get prop() {
// getter, the code executed when reading obj.prop
return someValue;
},
};
```
Properties defined using this syntax are own properties of the created object, and they are configurable and enumerable.
## Examples
### Defining a getter on new objects in object initializers
This will create a pseudo-property `latest` for object `obj`,
which will return the last array item in `log`.
```js
const obj = {
log: ["example", "test"],
get latest() {
if (this.log.length === 0) return undefined;
return this.log[this.log.length - 1];
},
};
console.log(obj.latest); // "test"
```
Note that attempting to assign a value to `latest` will not change it.
### Using getters in classes
You can use the exact same syntax to define public instance getters that are available on class instances. In classes, you don't need the comma separator between methods.
```js
class ClassWithGetSet {
#msg = "hello world";
get msg() {
return this.#msg;
}
set msg(x) {
this.#msg = `hello ${x}`;
}
}
const instance = new ClassWithGetSet();
console.log(instance.msg); // "hello world"
instance.msg = "cake";
console.log(instance.msg); // "hello cake"
```
Getter properties are defined on the `prototype` property of the class and are thus shared by all instances of the class. Unlike getter properties in object literals, getter properties in classes are not enumerable.
Static getters and private getters use similar syntaxes, which are described in the [`static`](/en-US/docs/Web/JavaScript/Reference/Classes/static) and [private properties](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties) pages.
### Deleting a getter using the `delete` operator
If you want to remove the getter, you can just {{jsxref("Operators/delete", "delete")}}
it:
```js
delete obj.latest;
```
### Defining a getter on existing objects using `defineProperty`
To append a getter to an existing object later at any time, use
{{jsxref("Object.defineProperty()")}}.
```js
const o = { a: 0 };
Object.defineProperty(o, "b", {
get() {
return this.a + 1;
},
});
console.log(o.b); // Runs the getter, which yields a + 1 (which is 1)
```
### Using a computed property name
```js
const expr = "foo";
const obj = {
get [expr]() {
return "bar";
},
};
console.log(obj.foo); // "bar"
```
### Defining static getters
```js
class MyConstants {
static get foo() {
return "foo";
}
}
console.log(MyConstants.foo); // 'foo'
MyConstants.foo = "bar";
console.log(MyConstants.foo); // 'foo', a static getter's value cannot be changed
```
### Smart / self-overwriting / lazy getters
Getters give you a way to _define_ a property of an object, but they do not
_calculate_ the property's value until it is accessed. A getter defers the cost
of calculating the value until the value is needed. If it is never needed, you never pay
the cost.
An additional optimization technique to lazify or delay the calculation of a property
value and cache it for later access are _smart_ (or _[memoized](https://en.wikipedia.org/wiki/Memoization)_) getters.
The value is calculated the first time the getter is called, and is then cached so
subsequent accesses return the cached value without recalculating it. This is useful in
the following situations:
- If the calculation of a property value is expensive (takes much RAM or CPU time,
spawns worker threads, retrieves remote file, etc.).
- If the value isn't needed just now. It will be used later, or in some case it's not
used at all.
- If it's used, it will be accessed several times, and there is no need to
re-calculate that value will never be changed or shouldn't be re-calculated.
> **Note:** This means that you shouldn't write a lazy getter for a property whose value you
> expect to change, because if the getter is lazy then it will not recalculate the
> value.
>
> Note that getters are not "lazy" or "memoized" by nature; you must implement this
> technique if you desire this behavior.
In the following example, the object has a getter as its own property. On getting the
property, the property is removed from the object and re-added, but implicitly as a data
property this time. Finally, the value gets returned.
```js
const obj = {
get notifier() {
delete this.notifier;
this.notifier = document.getElementById("bookmarked-notification-anchor");
return this.notifier;
},
};
```
### get vs. defineProperty
While using the `get` keyword and {{jsxref("Object.defineProperty()")}} have
similar results, there is a subtle difference between the two when used on
{{jsxref("classes")}}.
When using `get` the property will be defined on the instance's prototype,
while using {{jsxref("Object.defineProperty()")}} the property will be defined on the
instance it is applied to.
```js
class Example {
get hello() {
return "world";
}
}
const obj = new Example();
console.log(obj.hello);
// "world"
console.log(Object.getOwnPropertyDescriptor(obj, "hello"));
// undefined
console.log(
Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), "hello"),
);
// { configurable: true, enumerable: false, get: function get hello() { return 'world'; }, set: undefined }
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Working with objects](/en-US/docs/Web/JavaScript/Guide/Working_with_objects) guide
- [Functions](/en-US/docs/Web/JavaScript/Reference/Functions)
- [`set`](/en-US/docs/Web/JavaScript/Reference/Functions/set)
- {{jsxref("Object.defineProperty()")}}
- [Object initializer](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer)
- {{jsxref("Statements/class", "class")}}
- [Property accessors](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors)
- [Incompatible ES5 change: literal getter and setter functions must now have exactly zero or one arguments](https://whereswalden.com/2010/08/22/incompatible-es5-change-literal-getter-and-setter-functions-must-now-have-exactly-zero-or-one-arguments/) by Jeff Walden (2010)
- [More SpiderMonkey changes: ancient, esoteric, very rarely used syntax for creating getters and setters is being removed](https://whereswalden.com/2010/04/16/more-spidermonkey-changes-ancient-esoteric-very-rarely-used-syntax-for-creating-getters-and-setters-is-being-removed/) by Jeff Walden (2010)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/functions | data/mdn-content/files/en-us/web/javascript/reference/functions/set/index.md | ---
title: set
slug: Web/JavaScript/Reference/Functions/set
page-type: javascript-language-feature
browser-compat: javascript.functions.set
---
{{jsSidebar("Functions")}}
The **`set`** syntax binds an object property to a function to be called when there is an attempt to set that property. It can also be used in [classes](/en-US/docs/Web/JavaScript/Reference/Classes).
{{EmbedInteractiveExample("pages/js/functions-setter.html")}}
## Syntax
```js-nolint
{ set prop(val) { /* β¦ */ } }
{ set [expression](val) { /* β¦ */ } }
```
There are some additional syntax restrictions:
- A setter must have exactly one parameter.
### Parameters
- `prop`
- : The name of the property to bind to the given function. In the same way as other properties in [object initializers](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer), it can be a string literal, a number literal, or an identifier.
- `val`
- : An alias for the variable that holds the value attempted to be assigned to
`prop`.
- `expression`
- : You can also use expressions for a computed property name to bind to the given function.
## Description
In JavaScript, a setter can be used to execute a function whenever an attempt is made to change a property's value. Setters are most often used in conjunction with getters.
An object property is either a data property or an accessor property, but it cannot simultaneously be both. Read {{jsxref("Object.defineProperty()")}} for more information. The setter syntax allows you to specify the setter function in an object initializer.
```js
const obj = {
set prop() {
// setter, the code executed when setting obj.prop
},
}
```
Properties defined using this syntax are own properties of the created object, and they are configurable and enumerable.
## Examples
### Defining a setter on new objects in object initializers
The following example defines a pseudo-property `current` of object
`language`. When `current` is assigned a value, it updates
`log` with that value:
```js
const language = {
set current(name) {
this.log.push(name);
},
log: [],
};
language.current = "EN";
console.log(language.log); // ['EN']
language.current = "FA";
console.log(language.log); // ['EN', 'FA']
```
Note that `current` is not defined, and any attempts to access it will
result in `undefined`.
### Using setters in classes
You can use the exact same syntax to define public instance setters that are available on class instances. In classes, you don't need the comma separator between methods.
```js
class ClassWithGetSet {
#msg = "hello world";
get msg() {
return this.#msg;
}
set msg(x) {
this.#msg = `hello ${x}`;
}
}
const instance = new ClassWithGetSet();
console.log(instance.msg); // "hello world"
instance.msg = "cake";
console.log(instance.msg); // "hello cake"
```
Setter properties are defined on the `prototype` property of the class and are thus shared by all instances of the class. Unlike setter properties in object literals, setter properties in classes are not enumerable.
Static setters and private setters use similar syntaxes, which are described in the [`static`](/en-US/docs/Web/JavaScript/Reference/Classes/static) and [private properties](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties) pages.
### Removing a setter with the `delete` operator
If you want to remove the setter, you can just {{jsxref("Operators/delete", "delete")}}
it:
```js
delete language.current;
```
### Defining a setter on existing objects using `defineProperty`
To append a setter to an _existing_ object, use
{{jsxref("Object.defineProperty()")}}.
```js
const o = { a: 0 };
Object.defineProperty(o, "b", {
set(x) {
this.a = x / 2;
},
});
o.b = 10;
// Runs the setter, which assigns 10 / 2 (5) to the 'a' property
console.log(o.a); // 5
```
### Using a computed property name
```js
const expr = "foo";
const obj = {
baz: "bar",
set [expr](v) {
this.baz = v;
},
};
console.log(obj.baz); // "bar"
obj.foo = "baz";
// Run the setter
console.log(obj.baz); // "baz"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Working with objects](/en-US/docs/Web/JavaScript/Guide/Working_with_objects) guide
- [Functions](/en-US/docs/Web/JavaScript/Reference/Functions)
- [`get`](/en-US/docs/Web/JavaScript/Reference/Functions/get)
- {{jsxref("Object.defineProperty()")}}
- [Object initializer](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer)
- {{jsxref("Statements/class", "class")}}
- [Property accessors](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors)
- [Incompatible ES5 change: literal getter and setter functions must now have exactly zero or one arguments](https://whereswalden.com/2010/08/22/incompatible-es5-change-literal-getter-and-setter-functions-must-now-have-exactly-zero-or-one-arguments/) by Jeff Walden (2010)
- [More SpiderMonkey changes: ancient, esoteric, very rarely used syntax for creating getters and setters is being removed](https://whereswalden.com/2010/04/16/more-spidermonkey-changes-ancient-esoteric-very-rarely-used-syntax-for-creating-getters-and-setters-is-being-removed/) by Jeff Walden (2010)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/functions | data/mdn-content/files/en-us/web/javascript/reference/functions/arguments/index.md | ---
title: The arguments object
slug: Web/JavaScript/Reference/Functions/arguments
page-type: javascript-language-feature
browser-compat: javascript.functions.arguments
---
{{jsSidebar("Functions")}}
**`arguments`** is an array-like object accessible inside [functions](/en-US/docs/Web/JavaScript/Guide/Functions) that contains the values of the arguments passed to that function.
{{EmbedInteractiveExample("pages/js/functions-arguments.html")}}
## Description
> **Note:** In modern code, [rest parameters](/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters) should be preferred.
The `arguments` object is a local variable available within all non-[arrow](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) functions. You can refer to a function's arguments inside that function by using its `arguments` object. It has entries for each argument the function was called with, with the first entry's index at `0`.
For example, if a function is passed 3 arguments, you can access them as follows:
```js
arguments[0]; // first argument
arguments[1]; // second argument
arguments[2]; // third argument
```
The `arguments` object is useful for functions called with more arguments than they are formally declared to accept, called [_variadic functions_](https://en.wikipedia.org/wiki/Variadic_function), such as {{jsxref("Math.min()")}}. This example function accepts any number of string arguments and returns the longest one:
```js
function longestString() {
let longest = "";
for (let i = 0; i < arguments.length; i++) {
if (arguments[i].length > longest.length) {
longest = arguments[i];
}
}
return longest;
}
```
You can use {{jsxref("Functions/arguments/length", "arguments.length")}} to count how many arguments the function was called with. If you instead want to count how many parameters a function is declared to accept, inspect that function's {{jsxref("Function/length", "length")}} property.
### Assigning to indices
Each argument index can also be set or reassigned:
```js
arguments[1] = "new value";
```
Non-strict functions that only have simple parameters (that is, no rest, default, or destructured parameters) will sync the new value of parameters with the `arguments` object, and vice versa:
```js
function func(a) {
arguments[0] = 99; // updating arguments[0] also updates a
console.log(a);
}
func(10); // 99
function func2(a) {
a = 99; // updating a also updates arguments[0]
console.log(arguments[0]);
}
func2(10); // 99
```
Non-strict functions that _are_ passed [rest](/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters), [default](/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters), or [destructured](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) parameters will not sync new values assigned to parameters in the function body with the `arguments` object. Instead, the `arguments` object in non-strict functions with complex parameters will always reflect the values passed to the function when the function was called.
```js
function funcWithDefault(a = 55) {
arguments[0] = 99; // updating arguments[0] does not also update a
console.log(a);
}
funcWithDefault(10); // 10
function funcWithDefault2(a = 55) {
a = 99; // updating a does not also update arguments[0]
console.log(arguments[0]);
}
funcWithDefault2(10); // 10
// An untracked default parameter
function funcWithDefault3(a = 55) {
console.log(arguments[0]);
console.log(arguments.length);
}
funcWithDefault3(); // undefined; 0
```
This is the same behavior exhibited by all [strict-mode functions](/en-US/docs/Web/JavaScript/Reference/Strict_mode#making_eval_and_arguments_simpler), regardless of the type of parameters they are passed. That is, assigning new values to parameters in the body of the function never affects the `arguments` object, nor will assigning new values to the `arguments` indices affect the value of parameters, even when the function only has simple parameters.
> **Note:** You cannot write a `"use strict";` directive in the body of a function definition that accepts rest, default, or destructured parameters. Doing so will throw [a syntax error](/en-US/docs/Web/JavaScript/Reference/Errors/Strict_non_simple_params).
### arguments is an array-like object
`arguments` is an array-like object, which means that `arguments` has a {{jsxref("Functions/arguments/length", "length")}} property and properties indexed from zero, but it doesn't have {{jsxref("Array")}}'s built-in methods like {{jsxref("Array/forEach", "forEach()")}} or {{jsxref("Array/map", "map()")}}. However, it can be converted to a real `Array`, using one of [`slice()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice), {{jsxref("Array.from()")}}, or [spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax).
```js
const args = Array.prototype.slice.call(arguments);
// or
const args = Array.from(arguments);
// or
const args = [...arguments];
```
For common use cases, using it as an array-like object is sufficient, since it both [is iterable](/en-US/docs/Web/JavaScript/Reference/Functions/arguments/@@iterator) and has `length` and number indices. For example, [`Function.prototype.apply()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply) accepts array-like objects.
```js
function midpoint() {
return (
(Math.min.apply(null, arguments) + Math.max.apply(null, arguments)) / 2
);
}
console.log(midpoint(3, 1, 4, 1, 5)); // 3
```
## Properties
- {{jsxref("Functions/arguments/callee", "arguments.callee")}} {{deprecated_inline}}
- : Reference to the currently executing function that the arguments belong to. Forbidden in strict mode.
- {{jsxref("Functions/arguments/length", "arguments.length")}}
- : The number of arguments that were passed to the function.
- {{jsxref("Functions/arguments/@@iterator", "arguments[@@iterator]")}}
- : Returns a new {{jsxref("Array/@@iterator", "Array iterator", "", 0)}} object that contains the values for each index in `arguments`.
## Examples
### Defining a function that concatenates several strings
This example defines a function that concatenates several strings. The function's only formal argument is a string containing the characters that separate the items to concatenate.
```js
function myConcat(separator) {
const args = Array.prototype.slice.call(arguments, 1);
return args.join(separator);
}
```
You can pass as many arguments as you like to this function. It returns a string list using each argument in the list:
```js
myConcat(", ", "red", "orange", "blue");
// "red, orange, blue"
myConcat("; ", "elephant", "giraffe", "lion", "cheetah");
// "elephant; giraffe; lion; cheetah"
myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley");
// "sage. basil. oregano. pepper. parsley"
```
### Defining a function that creates HTML lists
This example defines a function that creates a string containing HTML for a list. The only formal argument for the function is a string that is `"u"` if the list is to be [unordered (bulleted)](/en-US/docs/Web/HTML/Element/ul), or `"o"` if the list is to be [ordered (numbered)](/en-US/docs/Web/HTML/Element/ol). The function is defined as follows:
```js
function list(type) {
let html = `<${type}l><li>`;
const args = Array.prototype.slice.call(arguments, 1);
html += args.join("</li><li>");
html += `</li></${type}l>`; // end list
return html;
}
```
You can pass any number of arguments to this function, and it adds each argument as a list item to a list of the type indicated. For example:
```js
list("u", "One", "Two", "Three");
// "<ul><li>One</li><li>Two</li><li>Three</li></ul>"
```
### Using typeof with arguments
The {{jsxref("Operators/typeof", "typeof")}} operator returns `'object'` when used with `arguments`
```js
console.log(typeof arguments); // 'object'
```
The type of individual arguments can be determined by indexing `arguments`:
```js
console.log(typeof arguments[0]); // returns the type of the first argument
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Functions](/en-US/docs/Web/JavaScript/Guide/Functions) guide
- [Functions](/en-US/docs/Web/JavaScript/Reference/Functions)
- [Rest parameters](/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/functions/arguments | data/mdn-content/files/en-us/web/javascript/reference/functions/arguments/callee/index.md | ---
title: arguments.callee
slug: Web/JavaScript/Reference/Functions/arguments/callee
page-type: javascript-instance-data-property
status:
- deprecated
browser-compat: javascript.functions.arguments.callee
---
{{jsSidebar("Functions")}}{{Deprecated_Header}}
> **Note:** Accessing `arguments.callee` in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode) will throw a {{jsxref("TypeError")}}. If a function must reference itself, either give the [function expression](/en-US/docs/Web/JavaScript/Reference/Operators/function) a name or use a [function declaration](/en-US/docs/Web/JavaScript/Reference/Statements/function).
The **`arguments.callee`** data property contains the currently executing function that the arguments belong to.
## Value
A reference to the currently executing function.
{{js_property_attributes(1, 0, 1)}}
> **Note:** `callee` is a data property only in non-strict functions with simple parameters (in which case the `arguments` object is also [auto-syncing](/en-US/docs/Web/JavaScript/Reference/Functions/arguments#assigning_to_indices)). Otherwise, it is an accessor property whose getter and setter both throw a {{jsxref("TypeError")}}.
## Description
`callee` is a property of the `arguments` object. It can be used to refer to the currently executing function inside the function body of that function. This is useful when the name of the function is unknown, such as within a function expression with no name (also called "anonymous functions").
(The text below is largely adapted from [a Stack Overflow answer by olliej](https://stackoverflow.com/questions/103598/why-was-the-arguments-callee-caller-property-deprecated-in-javascript/235760))
Early versions of JavaScript did not allow named function expressions, and for this reason you could not make a recursive function expression.
For example, this syntax worked:
```js
function factorial(n) {
return n <= 1 ? 1 : factorial(n - 1) * n;
}
[1, 2, 3, 4, 5].map(factorial);
```
but:
```js
[1, 2, 3, 4, 5].map(function (n) {
return n <= 1 ? 1 : /* what goes here? */ (n - 1) * n;
});
```
did not. To get around this `arguments.callee` was added so you could do
```js
[1, 2, 3, 4, 5].map(function (n) {
return n <= 1 ? 1 : arguments.callee(n - 1) * n;
});
```
However, the design of `arguments.callee` has multiple issues. The first problem is that the recursive call will get a different `this` value. For example:
```js
const global = this;
const sillyFunction = function (recursed) {
if (this !== global) {
console.log("This is:", this);
} else {
console.log("This is the global");
}
if (!recursed) {
return arguments.callee(true);
}
};
sillyFunction();
// This is the global
// This is: [object Arguments]
```
In addition, references to `arguments.callee` make inlining and tail recursion impossible in the general case. (You can achieve it in select cases through tracing, etc., but even the best code is suboptimal due to checks that would not otherwise be necessary.)
ECMAScript 3 resolved these issues by allowing named function expressions. For example:
```js
[1, 2, 3, 4, 5].map(function factorial(n) {
return n <= 1 ? 1 : factorial(n - 1) * n;
});
```
This has numerous benefits:
- the function can be called like any other from inside your code
- it does not create a variable in the outer scope ([except for IE 8 and below](https://kangax.github.io/nfe/#example_1_function_expression_identifier_leaks_into_an_enclosing_scope))
- it has better performance than accessing the arguments object
Strict mode has banned other properties that leak stack information, like the [`caller`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller) property of functions. This is because looking at the call stack has one single major effect: it makes a large number of optimizations impossible, or much more difficult. For example, if you cannot guarantee that a function `f` will not call an unknown function, it is not possible to inline `f`.
```js
function f(a, b, c, d, e) {
return a ? b * c : d * e;
}
```
If the JavaScript interpreter cannot guarantee that all the provided arguments are numbers at the point that the call is made, it needs to either insert checks for all the arguments before the inlined code, or it cannot inline the function. This means any call site that may have been trivially inlinable accumulates a large number of guards. Now in this particular case a smart interpreter should be able to rearrange the checks to be more optimal and not check any values that would not be used. However in many cases that's just not possible and therefore it becomes impossible to inline.
## Examples
### Using arguments.callee in an anonymous recursive function
A recursive function must be able to refer to itself. Typically, a function refers to itself by its name. However, an anonymous function (which can be created by a [function expression](/en-US/docs/Web/JavaScript/Reference/Operators/function) or the [`Function` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)) does not have a name. Therefore if there is no accessible variable referring to it, the only way the function can refer to itself is by `arguments.callee`.
The following example defines a function, which, in turn, defines and returns a factorial function. This example isn't very practical, and there are nearly no cases where the same result cannot be achieved with [named function expressions](/en-US/docs/Web/JavaScript/Reference/Operators/function).
```js
function create() {
return function (n) {
if (n <= 1) {
return 1;
}
return n * arguments.callee(n - 1);
};
}
const result = create()(5); // returns 120 (5 * 4 * 3 * 2 * 1)
```
### Recursion of anonymous functions with a Y-combinator
Although function expressions can now be named, [arrow functions](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) always remain anonymous, which means they cannot reference themselves without being assigned to a variable first. Fortunately, in Lambda calculus there's a very good solution which allows a function to both be anonymous and self-referential. The technique is called a [Y-combinator](https://en.wikipedia.org/wiki/Fixed-point_combinator#Y_combinator). Here we will not explain _how_ it works, only _that_ it works.
```js
// The Y-combinator: a utility function!
const Y = (hof) => ((x) => x(x))((x) => hof((y) => x(x)(y)));
console.log(
[1, 2, 3, 4, 5].map(
// Wrap the higher-order function in the Y-combinator
// "factorial" is not a function's name: it's introduced as a parameter
Y((factorial) => (n) => (n <= 1 ? 1 : factorial(n - 1) * n)),
),
);
// [ 1, 2, 6, 24, 120 ]
```
> **Note:** This method allocates a new closure for every iteration, which may significantly increase memory usage. It's only here to demonstrate the possibility, but should be avoided in production. Use a temporary variable or a named function expression instead.
## 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("Functions/arguments", "arguments")}}
- {{jsxref("Function.prototype.caller")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/functions/arguments | data/mdn-content/files/en-us/web/javascript/reference/functions/arguments/length/index.md | ---
title: arguments.length
slug: Web/JavaScript/Reference/Functions/arguments/length
page-type: javascript-instance-data-property
browser-compat: javascript.functions.arguments.length
---
{{jsSidebar("Functions")}}
The **`arguments.length`** data property contains the number of arguments passed to the function.
## Value
A non-negative integer.
{{js_property_attributes(1, 0, 1)}}
## Description
The `arguments.length` property provides the number of arguments actually passed to a function. This can be more or less than the defined parameter's count (see {{jsxref("Function.prototype.length")}}). For example, for the function below:
```js
function func1(a, b, c) {
console.log(arguments.length);
}
```
`func1.length` returns `3`, because `func1` declares three formal parameters. However, `func1(1, 2, 3, 4, 5)` logs `5`, because `func1` was called with five arguments. Similarly, `func1(1)` logs `1`, because `func1` was called with one argument.
## Examples
### Using arguments.length
In this example, we define a function that can add two or more numbers together.
```js
function adder(base /*, num1, β¦, numN */) {
base = Number(base);
for (let i = 1; i < arguments.length; i++) {
base += Number(arguments[i]);
}
return base;
}
```
## 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("Functions/arguments", "arguments")}}
- [`Function`: `length`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/functions/arguments | data/mdn-content/files/en-us/web/javascript/reference/functions/arguments/@@iterator/index.md | ---
title: arguments[@@iterator]()
slug: Web/JavaScript/Reference/Functions/arguments/@@iterator
page-type: javascript-instance-method
browser-compat: javascript.functions.arguments.@@iterator
---
{{jsSidebar("Functions")}}
The **`[@@iterator]()`** method of {{jsxref("Functions/arguments", "arguments")}} objects implements the [iterable protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) and allows `arguments` objects to be consumed by most syntaxes expecting iterables, such as the [spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and {{jsxref("Statements/for...of", "for...of")}} loops. It returns an [array iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) that yields the value of each index in the `arguments` object.
The initial value of this property is the same function object as the initial value of the {{jsxref("Array.prototype.values")}} property (and also the same as [`Array.prototype[@@iterator]`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@iterator)).
## Syntax
```js-nolint
arguments[Symbol.iterator]()
```
### Parameters
None.
### Return value
The same return value as {{jsxref("Array.prototype.values()")}}: a new [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) that yields the value of each index in the `arguments` object.
## Examples
### Iteration using for...of loop
Note that you seldom need to call this method directly. The existence of the `@@iterator` method makes `arguments` objects [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol), and iterating syntaxes like the `for...of` loop automatically call this method to obtain the iterator to loop over.
```js
function f() {
for (const letter of arguments) {
console.log(letter);
}
}
f("w", "y", "k", "o", "p");
```
### Manually hand-rolling the iterator
You may still manually call the `next()` method of the returned iterator object to achieve maximum control over the iteration process.
```js
function f() {
const argsIter = arguments[Symbol.iterator]();
console.log(argsIter.next().value); // a
console.log(argsIter.next().value); // b
console.log(argsIter.next().value); // c
console.log(argsIter.next().value); // d
console.log(argsIter.next().value); // e
}
f("w", "y", "k", "o", "p");
```
## 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("Functions/arguments", "arguments")}}
- {{jsxref("Array.prototype.values()")}}
- {{jsxref("Symbol.iterator")}}
- [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/functions | data/mdn-content/files/en-us/web/javascript/reference/functions/default_parameters/index.md | ---
title: Default parameters
slug: Web/JavaScript/Reference/Functions/Default_parameters
page-type: javascript-language-feature
browser-compat: javascript.functions.default_parameters
---
{{jsSidebar("Functions")}}
**Default function parameters** allow named parameters to be initialized with default values if no value or `undefined` is passed.
{{EmbedInteractiveExample("pages/js/functions-default.html")}}
## Syntax
```js-nolint
function fnName(param1 = defaultValue1, /* β¦, */ paramN = defaultValueN) {
// β¦
}
```
## Description
In JavaScript, function parameters default to {{jsxref("undefined")}}. However, it's often useful to set a different default value. This is where default parameters can help.
In the following example, if no value is provided for `b` when `multiply` is called, `b`'s value would be `undefined` when evaluating `a * b` and `multiply` would return `NaN`.
```js
function multiply(a, b) {
return a * b;
}
multiply(5, 2); // 10
multiply(5); // NaN !
```
In the past, the general strategy for setting defaults was to test parameter values in the function body and assign a value if they are `undefined`. In the following example, `b` is set to `1` if `multiply` is called with only one argument:
```js
function multiply(a, b) {
b = typeof b !== "undefined" ? b : 1;
return a * b;
}
multiply(5, 2); // 10
multiply(5); // 5
```
With default parameters, checks in the function body are no longer necessary. Now, you can assign `1` as the default value for `b` in the function head:
```js
function multiply(a, b = 1) {
return a * b;
}
multiply(5, 2); // 10
multiply(5); // 5
multiply(5, undefined); // 5
```
Parameters are still set left-to-right, overwriting default parameters even if there are later parameters without defaults.
```js
function f(x = 1, y) {
return [x, y];
}
f(); // [1, undefined]
f(2); // [2, undefined]
```
> **Note:** The first default parameter and all parameters after it will not contribute to the function's [`length`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length).
The default parameter initializers live in their own scope, which is a parent of the scope created for the function body.
This means that earlier parameters can be referred to in the initializers of later parameters. However, functions and variables declared in the function body cannot be referred to from default value parameter initializers; attempting to do so throws a run-time {{jsxref("ReferenceError")}}. This also includes [`var`](/en-US/docs/Web/JavaScript/Reference/Statements/var)-declared variables in the function body.
For example, the following function will throw a `ReferenceError` when invoked, because the default parameter value does not have access to the child scope of the function body:
```js example-bad
function f(a = go()) {
function go() {
return ":P";
}
}
f(); // ReferenceError: go is not defined
```
This function will print the value of the _parameter_ `a`, because the variable `var a` is hoisted only to the top of the scope created for the function body, not the parent scope created for the parameter list, so its value is not visible to `b`.
```js example-bad
function f(a, b = () => console.log(a)) {
var a = 1;
b();
}
f(); // undefined
f(5); // 5
```
## Examples
### Passing undefined vs. other falsy values
In the second call in this example, even if the first argument is set explicitly to `undefined` (though not `null` or other {{Glossary("falsy")}} values), the value of the `num` argument is still the default.
```js
function test(num = 1) {
console.log(typeof num);
}
test(); // 'number' (num is set to 1)
test(undefined); // 'number' (num is set to 1 too)
// test with other falsy values:
test(""); // 'string' (num is set to '')
test(null); // 'object' (num is set to null)
```
### Evaluated at call time
The default argument is evaluated at _call time_. Unlike with Python (for example), a new object is created each time the function is called.
```js
function append(value, array = []) {
array.push(value);
return array;
}
append(1); // [1]
append(2); // [2], not [1, 2]
```
This even applies to functions and variables:
```js
function callSomething(thing = something()) {
return thing;
}
let numberOfTimesCalled = 0;
function something() {
numberOfTimesCalled += 1;
return numberOfTimesCalled;
}
callSomething(); // 1
callSomething(); // 2
```
### Earlier parameters are available to later default parameters
Parameters defined earlier (to the left) are available to later default parameters:
```js
function greet(name, greeting, message = `${greeting} ${name}`) {
return [name, greeting, message];
}
greet("David", "Hi"); // ["David", "Hi", "Hi David"]
greet("David", "Hi", "Happy Birthday!"); // ["David", "Hi", "Happy Birthday!"]
```
This functionality can be approximated like this, which demonstrates how many edge cases are handled:
```js
function go() {
return ":P";
}
function withDefaults(
a,
b = 5,
c = b,
d = go(),
e = this,
f = arguments,
g = this.value,
) {
return [a, b, c, d, e, f, g];
}
function withoutDefaults(a, b, c, d, e, f, g) {
switch (arguments.length) {
case 0:
case 1:
b = 5;
case 2:
c = b;
case 3:
d = go();
case 4:
e = this;
case 5:
f = arguments;
case 6:
g = this.value;
}
return [a, b, c, d, e, f, g];
}
withDefaults.call({ value: "=^_^=" });
// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="]
withoutDefaults.call({ value: "=^_^=" });
// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="]
```
### Destructured parameter with default value assignment
You can use default value assignment with the [destructuring assignment](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) syntax.
A common way of doing that is to set an empty object/array as the default value for the destructured parameter; for example: `[x = 1, y = 2] = []`. This makes it possible to pass nothing to the function and still have those values prefilled:
```js
function preFilledArray([x = 1, y = 2] = []) {
return x + y;
}
preFilledArray(); // 3
preFilledArray([]); // 3
preFilledArray([2]); // 4
preFilledArray([2, 3]); // 5
// Works the same for objects:
function preFilledObject({ z = 3 } = {}) {
return z;
}
preFilledObject(); // 3
preFilledObject({}); // 3
preFilledObject({ z: 2 }); // 2
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Functions](/en-US/docs/Web/JavaScript/Guide/Functions) guide
- [Functions](/en-US/docs/Web/JavaScript/Reference/Functions)
- [Rest parameters](/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters)
- [Nullish coalescing operator (`??`)](/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/functions | data/mdn-content/files/en-us/web/javascript/reference/functions/rest_parameters/index.md | ---
title: Rest parameters
slug: Web/JavaScript/Reference/Functions/rest_parameters
page-type: javascript-language-feature
browser-compat: javascript.functions.rest_parameters
---
{{jsSidebar("Functions")}}
The **rest parameter** syntax allows a function to accept an indefinite number of arguments as an array, providing a way to represent [variadic functions](https://en.wikipedia.org/wiki/Variadic_function) in JavaScript.
{{EmbedInteractiveExample("pages/js/functions-restparameters.html", "taller")}}
## Syntax
```js-nolint
function f(a, b, ...theArgs) {
// β¦
}
```
## Description
A function definition's last parameter can be prefixed with `...` (three U+002E FULL STOP characters), which will cause all remaining (user supplied) parameters to be placed within an [`Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) object.
```js
function myFun(a, b, ...manyMoreArgs) {
console.log("a", a);
console.log("b", b);
console.log("manyMoreArgs", manyMoreArgs);
}
myFun("one", "two", "three", "four", "five", "six");
// Console Output:
// a, one
// b, two
// manyMoreArgs, ["three", "four", "five", "six"]
```
A function definition can only have one rest parameter, and the rest parameter must be the last parameter in the function definition.
```js-nolint example-bad
function wrong1(...one, ...wrong) {}
function wrong2(...wrong, arg2, arg3) {}
```
The rest parameter is not counted towards the function's [`length`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length) property.
### The difference between rest parameters and the arguments object
There are three main differences between rest parameters and the {{jsxref("Functions/arguments", "arguments")}} object:
- The `arguments` object is **not a real array**, while rest parameters are {{jsxref("Array")}} instances, meaning methods like {{jsxref("Array/sort", "sort()")}}, {{jsxref("Array/map", "map()")}}, {{jsxref("Array/forEach", "forEach()")}} or {{jsxref("Array/pop", "pop()")}} can be applied on it directly.
- The `arguments` object has the additional (deprecated) [`callee`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee) property.
- In a non-strict function with simple parameters, the `arguments` object [syncs its indices with the values of parameters](/en-US/docs/Web/JavaScript/Reference/Functions/arguments#assigning_to_indices). The rest parameter array never updates its value when the named parameters are re-assigned.
- The rest parameter bundles all the _extra_ parameters into a single array, but does not contain any named argument defined _before_ the `...restParam`. The `arguments` object contains all of the parameters β including the parameters in the `...restParam` array β bundled into one array-like object.
## Examples
### Using rest parameters
In this example, the first argument is mapped to `a` and the second to `b`, so these named arguments are used as normal.
However, the third argument, `manyMoreArgs`, will be an array that contains the third, fourth, fifth, sixth, β¦, nth β as many arguments as the user specifies.
```js
function myFun(a, b, ...manyMoreArgs) {
console.log("a", a);
console.log("b", b);
console.log("manyMoreArgs", manyMoreArgs);
}
myFun("one", "two", "three", "four", "five", "six");
// a, "one"
// b, "two"
// manyMoreArgs, ["three", "four", "five", "six"] <-- an array
```
Below, even though there is just one value, the last argument still gets put into an array.
```js
// Using the same function definition from example above
myFun("one", "two", "three");
// a, "one"
// b, "two"
// manyMoreArgs, ["three"] <-- an array with just one value
```
Below, the third argument isn't provided, but `manyMoreArgs` is still an array (albeit an empty one).
```js
// Using the same function definition from example above
myFun("one", "two");
// a, "one"
// b, "two"
// manyMoreArgs, [] <-- still an array
```
Below, only one argument is provided, so `b` gets the default value `undefined`, but `manyMoreArgs` is still an empty array.
```js
// Using the same function definition from example above
myFun("one");
// a, "one"
// b, undefined
// manyMoreArgs, [] <-- still an array
```
### Argument length
Since `theArgs` is an array, a count of its elements is given by the {{jsxref("Array/length", "length")}} property. If the function's only parameter is a rest parameter, `restParams.length` will be equal to [`arguments.length`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments/length).
```js
function fun1(...theArgs) {
console.log(theArgs.length);
}
fun1(); // 0
fun1(5); // 1
fun1(5, 6, 7); // 3
```
### Using rest parameters in combination with ordinary parameters
In the next example, a rest parameter is used to collect all parameters after the first parameter into an array. Each one of the parameter values collected into the array is then multiplied by the first parameter, and the array is returned:
```js
function multiply(multiplier, ...theArgs) {
return theArgs.map((element) => multiplier * element);
}
const arr = multiply(2, 15, 25, 42);
console.log(arr); // [30, 50, 84]
```
### From arguments to an array
{{jsxref("Array")}} methods can be used on rest parameters, but not on the `arguments` object:
```js
function sortRestArgs(...theArgs) {
const sortedArgs = theArgs.sort();
return sortedArgs;
}
console.log(sortRestArgs(5, 3, 7, 1)); // 1, 3, 5, 7
function sortArguments() {
const sortedArgs = arguments.sort();
return sortedArgs; // this will never happen
}
console.log(sortArguments(5, 3, 7, 1));
// throws a TypeError (arguments.sort is not a function)
```
Rest parameters were introduced to reduce the boilerplate code that was commonly used for converting a set of arguments to an array.
Before rest parameters, `arguments` need to be converted to a normal array before calling array methods on them:
```js
function fn(a, b) {
const normalArray = Array.prototype.slice.call(arguments);
// β or β
const normalArray2 = [].slice.call(arguments);
// β or β
const normalArrayFrom = Array.from(arguments);
const first = normalArray.shift(); // OK, gives the first argument
const firstBad = arguments.shift(); // ERROR (arguments is not a normal array)
}
```
Now, you can easily gain access to a normal array using a rest parameter:
```js
function fn(...args) {
const normalArray = args;
const first = normalArray.shift(); // OK, gives the first argument
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Functions](/en-US/docs/Web/JavaScript/Guide/Functions) guide
- [Functions](/en-US/docs/Web/JavaScript/Reference/Functions)
- [Spread syntax (`...`)](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)
- [Default parameters](/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters)
- {{jsxref("Functions/arguments", "arguments")}}
- {{jsxref("Array")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/functions | data/mdn-content/files/en-us/web/javascript/reference/functions/arrow_functions/index.md | ---
title: Arrow function expressions
slug: Web/JavaScript/Reference/Functions/Arrow_functions
page-type: javascript-language-feature
browser-compat: javascript.functions.arrow_functions
---
{{jsSidebar("Functions")}}
An **arrow function expression** is a compact alternative to a traditional [function expression](/en-US/docs/Web/JavaScript/Reference/Operators/function), with some semantic differences and deliberate limitations in usage:
- Arrow functions don't have their own {{Glossary("binding", "bindings")}} to [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this), [`arguments`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments), or [`super`](/en-US/docs/Web/JavaScript/Reference/Operators/super), and should not be used as [methods](/en-US/docs/Glossary/Method).
- Arrow functions cannot be used as [constructors](/en-US/docs/Glossary/Constructor). Calling them with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new) throws a {{jsxref("TypeError")}}. They also don't have access to the [`new.target`](/en-US/docs/Web/JavaScript/Reference/Operators/new.target) keyword.
- Arrow functions cannot use [`yield`](/en-US/docs/Web/JavaScript/Reference/Operators/yield) within their body and cannot be created as generator functions.
{{EmbedInteractiveExample("pages/js/functions-arrow.html")}}
## Syntax
```js-nolint
() => expression
param => expression
(param) => expression
(param1, paramN) => expression
() => {
statements
}
param => {
statements
}
(param1, paramN) => {
statements
}
```
[Rest parameters](/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters), [default parameters](/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters), and [destructuring](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) within params are supported, and always require parentheses:
```js-nolint
(a, b, ...r) => expression
(a = 400, b = 20, c) => expression
([a, b] = [10, 20]) => expression
({ a, b } = { a: 10, b: 20 }) => expression
```
Arrow functions can be [`async`](/en-US/docs/Web/JavaScript/Reference/Statements/async_function) by prefixing the expression with the `async` keyword.
```js-nolint
async param => expression
async (param1, param2, ...paramN) => {
statements
}
```
## Description
Let's decompose a traditional anonymous function down to the simplest arrow function step-by-step. Each step along the way is a valid arrow function.
> **Note:** Traditional function expressions and arrow functions have more differences than their syntax. We will introduce their behavior differences in more detail in the next few subsections.
```js-nolint
// Traditional anonymous function
(function (a) {
return a + 100;
});
// 1. Remove the word "function" and place arrow between the argument and opening body brace
(a) => {
return a + 100;
};
// 2. Remove the body braces and word "return" β the return is implied.
(a) => a + 100;
// 3. Remove the parameter parentheses
a => a + 100;
```
In the example above, both the parentheses around the parameter and the braces around the function body may be omitted. However, they can only be omitted in certain cases.
The parentheses can only be omitted if the function has a single simple parameter. If it has multiple parameters, no parameters, or default, destructured, or rest parameters, the parentheses around the parameter list are required.
```js
// Traditional anonymous function
(function (a, b) {
return a + b + 100;
});
// Arrow function
(a, b) => a + b + 100;
const a = 4;
const b = 2;
// Traditional anonymous function (no parameters)
(function () {
return a + b + 100;
});
// Arrow function (no parameters)
() => a + b + 100;
```
The braces can only be omitted if the function directly returns an expression. If the body has additional lines of processing, the braces are required β and so is the `return` keyword. Arrow functions cannot guess what or when you want to return.
```js
// Traditional anonymous function
(function (a, b) {
const chuck = 42;
return a + b + chuck;
});
// Arrow function
(a, b) => {
const chuck = 42;
return a + b + chuck;
};
```
Arrow functions are always unnamed. If the arrow function needs to call itself, use a named function expression instead. You can also assign the arrow function to a variable so it has a name.
```js
// Traditional Function
function bob(a) {
return a + 100;
}
// Arrow Function
const bob2 = (a) => a + 100;
```
### Function body
Arrow functions can have either an _expression body_ or the usual _block body_.
In an expression body, only a single expression is specified, which becomes the implicit return value. In a block body, you must use an explicit `return` statement.
```js
const func = (x) => x * x;
// expression body syntax, implied "return"
const func2 = (x, y) => {
return x + y;
};
// with block body, explicit "return" needed
```
Returning object literals using the expression body syntax `(params) => { object: literal }` does not work as expected.
```js-nolint example-bad
const func = () => { foo: 1 };
// Calling func() returns undefined!
const func2 = () => { foo: function () {} };
// SyntaxError: function statement requires a name
const func3 = () => { foo() {} };
// SyntaxError: Unexpected token '{'
```
This is because JavaScript only sees the arrow function as having an expression body if the token following the arrow is not a left brace, so the code inside braces ({}) is parsed as a sequence of statements, where `foo` is a [label](/en-US/docs/Web/JavaScript/Reference/Statements/label), not a key in an object literal.
To fix this, wrap the object literal in parentheses:
```js example-good
const func = () => ({ foo: 1 });
```
### Cannot be used as methods
Arrow function expressions should only be used for non-method functions because they do not have their own `this`. Let's see what happens when we try to use them as methods:
```js
"use strict";
const obj = {
i: 10,
b: () => console.log(this.i, this),
c() {
console.log(this.i, this);
},
};
obj.b(); // logs undefined, Window { /* β¦ */ } (or the global object)
obj.c(); // logs 10, Object { /* β¦ */ }
```
Another example involving {{jsxref("Object.defineProperty()")}}:
```js
"use strict";
const obj = {
a: 10,
};
Object.defineProperty(obj, "b", {
get: () => {
console.log(this.a, typeof this.a, this); // undefined 'undefined' Window { /* β¦ */ } (or the global object)
return this.a + 10; // represents global object 'Window', therefore 'this.a' returns 'undefined'
},
});
```
Because a [class](/en-US/docs/Web/JavaScript/Reference/Classes)'s body has a `this` context, arrow functions as [class fields](/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields) close over the class's `this` context, and the `this` inside the arrow function's body will correctly point to the instance (or the class itself, for [static fields](/en-US/docs/Web/JavaScript/Reference/Classes/static)). However, because it is a [closure](/en-US/docs/Web/JavaScript/Closures), not the function's own binding, the value of `this` will not change based on the execution context.
```js
class C {
a = 1;
autoBoundMethod = () => {
console.log(this.a);
};
}
const c = new C();
c.autoBoundMethod(); // 1
const { autoBoundMethod } = c;
autoBoundMethod(); // 1
// If it were a normal method, it should be undefined in this case
```
Arrow function properties are often said to be "auto-bound methods", because the equivalent with normal methods is:
```js
class C {
a = 1;
constructor() {
this.method = this.method.bind(this);
}
method() {
console.log(this.a);
}
}
```
> **Note:** Class fields are defined on the _instance_, not on the _prototype_, so every instance creation would create a new function reference and allocate a new closure, potentially leading to more memory usage than a normal unbound method.
For similar reasons, the [`call()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call), [`apply()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply), and [`bind()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) methods are not useful when called on arrow functions, because arrow functions establish `this` based on the scope the arrow function is defined within, and the `this` value does not change based on how the function is invoked.
### No binding of arguments
Arrow functions do not have their own [`arguments`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments) object. Thus, in this example, `arguments` is a reference to the arguments of the enclosing scope:
```js
function foo(n) {
const f = () => arguments[0] + n; // foo's implicit arguments binding. arguments[0] is n
return f();
}
foo(3); // 3 + 3 = 6
```
> **Note:** You cannot declare a variable called `arguments` in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode#making_eval_and_arguments_simpler), so the code above would be a syntax error. This makes the scoping effect of `arguments` much easier to comprehend.
In most cases, using [rest parameters](/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters)
is a good alternative to using an `arguments` object.
```js
function foo(n) {
const f = (...args) => args[0] + n;
return f(10);
}
foo(1); // 11
```
### Cannot be used as constructors
Arrow functions cannot be used as constructors and will throw an error when called with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). They also do not have a [`prototype`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype) property.
```js
const Foo = () => {};
const foo = new Foo(); // TypeError: Foo is not a constructor
console.log("prototype" in Foo); // false
```
### Cannot be used as generators
The [`yield`](/en-US/docs/Web/JavaScript/Reference/Operators/yield) keyword cannot be used in an arrow function's body (except when used within generator functions further nested within the arrow function). As a consequence, arrow functions cannot be used as generators.
### Line break before arrow
An arrow function cannot contain a line break between its parameters and its arrow.
```js-nolint example-bad
const func = (a, b, c)
=> 1;
// SyntaxError: Unexpected token '=>'
```
For the purpose of formatting, you may put the line break after the arrow or use parentheses/braces around the function body, as shown below. You can also put line breaks between parameters.
```js-nolint
const func = (a, b, c) =>
1;
const func2 = (a, b, c) => (
1
);
const func3 = (a, b, c) => {
return 1;
};
const func4 = (
a,
b,
c,
) => 1;
```
### Precedence of arrow
Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with [operator precedence](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence) compared to regular functions.
```js-nolint example-bad
let callback;
callback = callback || () => {};
// SyntaxError: invalid arrow-function arguments
```
Because `=>` has a lower precedence than most operators, parentheses are necessary to avoid `callback || ()` being parsed as the arguments list of the arrow function.
```js example-good
callback = callback || (() => {});
```
## Examples
### Using arrow functions
```js
// An empty arrow function returns undefined
const empty = () => {};
(() => "foobar")();
// Returns "foobar"
// (this is an Immediately Invoked Function Expression)
const simple = (a) => (a > 15 ? 15 : a);
simple(16); // 15
simple(10); // 10
const max = (a, b) => (a > b ? a : b);
// Easy array filtering, mapping, etc.
const arr = [5, 6, 13, 0, 1, 18, 23];
const sum = arr.reduce((a, b) => a + b);
// 66
const even = arr.filter((v) => v % 2 === 0);
// [6, 0, 18]
const double = arr.map((v) => v * 2);
// [10, 12, 26, 0, 2, 36, 46]
// More concise promise chains
promise
.then((a) => {
// β¦
})
.then((b) => {
// β¦
});
// Parameterless arrow functions that are visually easier to parse
setTimeout(() => {
console.log("I happen sooner");
setTimeout(() => {
// deeper code
console.log("I happen later");
}, 1);
}, 1);
```
### Using call, bind, and apply
The [`call()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call), [`apply()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply), and [`bind()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) methods work as expected with traditional functions, because we establish the scope for each of the methods:
```js
const obj = {
num: 100,
};
// Setting "num" on globalThis to show how it is NOT used.
globalThis.num = 42;
// A simple traditional function to operate on "this"
const add = function (a, b, c) {
return this.num + a + b + c;
};
console.log(add.call(obj, 1, 2, 3)); // 106
console.log(add.apply(obj, [1, 2, 3])); // 106
const boundAdd = add.bind(obj);
console.log(boundAdd(1, 2, 3)); // 106
```
With arrow functions, since our `add` function is essentially created on the `globalThis` (global) scope, it will assume `this` is the `globalThis`.
```js
const obj = {
num: 100,
};
// Setting "num" on globalThis to show how it gets picked up.
globalThis.num = 42;
// Arrow function
const add = (a, b, c) => this.num + a + b + c;
console.log(add.call(obj, 1, 2, 3)); // 48
console.log(add.apply(obj, [1, 2, 3])); // 48
const boundAdd = add.bind(obj);
console.log(boundAdd(1, 2, 3)); // 48
```
Perhaps the greatest benefit of using arrow functions is with methods like {{domxref("setTimeout()")}} and {{domxref("EventTarget/addEventListener()", "EventTarget.prototype.addEventListener()")}} that usually require some kind of closure, `call()`, `apply()`, or `bind()` to ensure that the function is executed in the proper scope.
With traditional function expressions, code like this does not work as expected:
```js
const obj = {
count: 10,
doSomethingLater() {
setTimeout(function () {
// the function executes on the window scope
this.count++;
console.log(this.count);
}, 300);
},
};
obj.doSomethingLater(); // logs "NaN", because the property "count" is not in the window scope.
```
With arrow functions, the `this` scope is more easily preserved:
```js
const obj = {
count: 10,
doSomethingLater() {
// The method syntax binds "this" to the "obj" context.
setTimeout(() => {
// Since the arrow function doesn't have its own binding and
// setTimeout (as a function call) doesn't create a binding
// itself, the "obj" context of the outer method is used.
this.count++;
console.log(this.count);
}, 300);
},
};
obj.doSomethingLater(); // logs 11
```
## 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")}}
- [`function` expression](/en-US/docs/Web/JavaScript/Reference/Operators/function)
- [ES6 In Depth: Arrow functions](https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/) on hacks.mozilla.org (2015)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/functions | data/mdn-content/files/en-us/web/javascript/reference/functions/method_definitions/index.md | ---
title: Method definitions
slug: Web/JavaScript/Reference/Functions/Method_definitions
page-type: javascript-language-feature
browser-compat: javascript.functions.method_definitions
---
{{jsSidebar("Functions")}}
**Method definition** is a shorter syntax for defining a function property in an object initializer. It can also be used in [classes](/en-US/docs/Web/JavaScript/Reference/Classes).
{{EmbedInteractiveExample("pages/js/functions-definitions.html")}}
## Syntax
```js-nolint
({
property(parameters) {},
*generator(parameters) {},
async property(parameters) {},
async *generator(parameters) {},
// with computed keys
[expression](parameters) {},
*[expression](parameters) {},
async [expression](parameters) {},
async *[expression](parameters) {},
})
```
## Description
The shorthand syntax is similar to the [getter](/en-US/docs/Web/JavaScript/Reference/Functions/get) and [setter](/en-US/docs/Web/JavaScript/Reference/Functions/set) syntax.
Given the following code:
```js
const obj = {
foo: function () {
// β¦
},
bar: function () {
// β¦
},
};
```
You are now able to shorten this to:
```js
const obj = {
foo() {
// β¦
},
bar() {
// β¦
},
};
```
Properties defined using this syntax are own properties of the created object, and they are configurable, enumerable, and writable, just like normal properties.
[`function*`](/en-US/docs/Web/JavaScript/Reference/Statements/function*), [`async function`](/en-US/docs/Web/JavaScript/Reference/Statements/async_function), and [`async function*`](/en-US/docs/Web/JavaScript/Reference/Statements/async_function*) properties all have their respective method syntaxes; see examples below.
However, note that the method syntax is not equivalent to a normal property with a function as its value β there are semantic differences. This makes methods defined in object literals more consistent with methods in [classes](/en-US/docs/Web/JavaScript/Reference/Classes).
### Method definitions are not constructable
Methods cannot be constructors! They will throw a {{jsxref("TypeError")}} if you try to instantiate them. On the other hand, a property created as a function can be used as a constructor.
```js example-bad
const obj = {
method() {},
};
new obj.method(); // TypeError: obj.method is not a constructor
```
### Using super in method definitions
Only functions defined as methods have access to the [`super`](/en-US/docs/Web/JavaScript/Reference/Operators/super) keyword. `super.prop` looks up the property on the prototype of the object that the method was initialized on.
```js-nolint example-bad
const obj = {
__proto__: {
prop: "foo",
},
notAMethod: function () {
console.log(super.prop); // SyntaxError: 'super' keyword unexpected here
},
};
```
## Examples
### Using method definitions
```js
const obj = {
a: "foo",
b() {
return this.a;
},
};
console.log(obj.b()); // "foo"
```
### Method definitions in classes
You can use the exact same syntax to define public instance methods that are available on class instances. In classes, you don't need the comma separator between methods.
```js
class ClassWithPublicInstanceMethod {
publicMethod() {
return "hello world";
}
secondPublicMethod() {
return "goodbye world";
}
}
const instance = new ClassWithPublicInstanceMethod();
console.log(instance.publicMethod()); // "hello world"
```
Public instance methods are defined on the `prototype` property of the class and are thus shared by all instances of the class. They are writable, non-enumerable, and configurable.
Inside instance methods, [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this) and [`super`](/en-US/docs/Web/JavaScript/Reference/Operators/super) work like in normal methods. Usually, `this` refers to the instance itself. In subclasses, `super` lets you access the prototype of the object that the method is attached to, allowing you to call methods from the superclass.
```js
class BaseClass {
msg = "hello world";
basePublicMethod() {
return this.msg;
}
}
class SubClass extends BaseClass {
subPublicMethod() {
return super.basePublicMethod();
}
}
const instance = new SubClass();
console.log(instance.subPublicMethod()); // "hello world"
```
Static methods and private methods use similar syntaxes, which are described in the [`static`](/en-US/docs/Web/JavaScript/Reference/Classes/static) and [private properties](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties) pages.
### Computed property names
The method syntax also supports [computed property names](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names).
```js
const bar = {
foo0: function () {
return 0;
},
foo1() {
return 1;
},
["foo" + 2]() {
return 2;
},
};
console.log(bar.foo0()); // 0
console.log(bar.foo1()); // 1
console.log(bar.foo2()); // 2
```
### Generator methods
Note that the asterisk (`*`) in the generator method syntax must be _before_ the generator property name. (That is, `* g(){}` will work, but `g *(){}` will not.)
```js
// Using a named property
const obj = {
g: function* () {
let index = 0;
while (true) {
yield index++;
}
},
};
// The same object using shorthand syntax
const obj2 = {
*g() {
let index = 0;
while (true) {
yield index++;
}
},
};
const it = obj2.g();
console.log(it.next().value); // 0
console.log(it.next().value); // 1
```
### Async methods
```js
// Using a named property
const obj = {
f: async function () {
await somePromise;
},
};
// The same object using shorthand syntax
const obj2 = {
async f() {
await somePromise;
},
};
```
### Async generator methods
```js
const obj = {
f: async function* () {
yield 1;
yield 2;
yield 3;
},
};
// The same object using shorthand syntax
const obj2 = {
async *f() {
yield 1;
yield 2;
yield 3;
},
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Working with objects](/en-US/docs/Web/JavaScript/Guide/Working_with_objects) guide
- [Functions](/en-US/docs/Web/JavaScript/Reference/Functions)
- [`get`](/en-US/docs/Web/JavaScript/Reference/Functions/get)
- [`set`](/en-US/docs/Web/JavaScript/Reference/Functions/set)
- [Object initializer](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer)
- {{jsxref("Statements/class", "class")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference | data/mdn-content/files/en-us/web/javascript/reference/template_literals/index.md | ---
title: Template literals (Template strings)
slug: Web/JavaScript/Reference/Template_literals
page-type: javascript-language-feature
browser-compat: javascript.grammar.template_literals
---
{{jsSidebar("More")}}
**Template literals** are literals delimited with backtick (`` ` ``) characters, allowing for [multi-line strings](#multi-line_strings), [string interpolation](#string_interpolation) with embedded expressions, and special constructs called [tagged templates](#tagged_templates).
Template literals are sometimes informally called _template strings_, because they are used most commonly for [string interpolation](#string_interpolation) (to create strings by doing substitution of placeholders). However, a tagged template literal may not result in a string; it can be used with a custom [tag function](#tagged_templates) to perform whatever operations you want on the different parts of the template literal.
## Syntax
```js-nolint
`string text`
`string text line 1
string text line 2`
`string text ${expression} string text`
tagFunction`string text ${expression} string text`
```
### Parameters
- `string text`
- : The string text that will become part of the template literal. Almost all characters are allowed literally, including [line breaks](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#line_terminators) and other [whitespace characters](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#white_space). However, invalid escape sequences will cause a syntax error, unless a [tag function](#tagged_templates_and_escape_sequences) is used.
- `expression`
- : An expression to be inserted in the current position, whose value is converted to a string or passed to `tagFunction`.
- `tagFunction`
- : If specified, it will be called with the template strings array and substitution expressions, and the return value becomes the value of the template literal. See [tagged templates](#tagged_templates).
## Description
Template literals are enclosed by backtick (`` ` ``) characters instead of double or single quotes.
Along with having normal strings, template literals can also contain other parts called _placeholders_, which are embedded expressions delimited by a dollar sign and curly braces: `${expression}`. The strings and placeholders get passed to a function β either a default function, or a function you supply. The default function (when you don't supply your own) just performs [string interpolation](#string_interpolation) to do substitution of the placeholders and then concatenate the parts into a single string.
To supply a function of your own, precede the template literal with a function name; the result is called a [**tagged template**](#tagged_templates). In that case, the template literal is passed to your tag function, where you can then perform whatever operations you want on the different parts of the template literal.
To escape a backtick in a template literal, put a backslash (`\`) before the backtick.
```js
`\`` === "`"; // true
```
Dollar signs can be escaped as well to prevent interpolation.
```js
`\${1}` === "${1}"; // true
```
### Multi-line strings
Any newline characters inserted in the source are part of the template literal.
Using normal strings, you would have to use the following syntax in order to get multi-line strings:
```js
console.log("string text line 1\n" + "string text line 2");
// "string text line 1
// string text line 2"
```
Using template literals, you can do the same with this:
```js
console.log(`string text line 1
string text line 2`);
// "string text line 1
// string text line 2"
```
### String interpolation
Without template literals, when you want to combine output from expressions with strings, you'd [concatenate them](/en-US/docs/Learn/JavaScript/First_steps/Strings#concatenation_using) using the [addition operator](/en-US/docs/Web/JavaScript/Reference/Operators/Addition) `+`:
```js
const a = 5;
const b = 10;
console.log("Fifteen is " + (a + b) + " and\nnot " + (2 * a + b) + ".");
// "Fifteen is 15 and
// not 20."
```
That can be hard to read β especially when you have multiple expressions.
With template literals, you can avoid the concatenation operator β and improve the readability of your code β by using placeholders of the form `${expression}` to perform substitutions for embedded expressions:
```js
const a = 5;
const b = 10;
console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);
// "Fifteen is 15 and
// not 20."
```
Note that there's a mild difference between the two syntaxes. Template literals [coerce their expressions directly to strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), while addition coerces its operands to primitives first. For more information, see the reference page for the [`+` operator](/en-US/docs/Web/JavaScript/Reference/Operators/Addition).
### Nesting templates
In certain cases, nesting a template is the easiest (and perhaps more readable) way to have configurable strings. Within a backtick-delimited template, it is simple to allow inner backticks by using them inside an `${expression}` placeholder within the template.
For example, without template literals, if you wanted to return a certain value based on a particular condition, you could do something like the following:
```js example-bad
let classes = "header";
classes += isLargeScreen()
? ""
: item.isCollapsed
? " icon-expander"
: " icon-collapser";
```
With a template literal but without nesting, you could do this:
```js example-bad
const classes = `header ${
isLargeScreen() ? "" : item.isCollapsed ? "icon-expander" : "icon-collapser"
}`;
```
With nesting of template literals, you can do this:
```js example-good
const classes = `header ${
isLargeScreen() ? "" : `icon-${item.isCollapsed ? "expander" : "collapser"}`
}`;
```
### Tagged templates
A more advanced form of template literals are _tagged_ templates.
Tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions.
The tag function can then perform whatever operations on these arguments you wish, and return the manipulated string. (Alternatively, it can return something completely different, as described in one of the following examples.)
The name of the function used for the tag can be whatever you want.
```js
const person = "Mike";
const age = 28;
function myTag(strings, personExp, ageExp) {
const str0 = strings[0]; // "That "
const str1 = strings[1]; // " is a "
const str2 = strings[2]; // "."
const ageStr = ageExp < 100 ? "youngster" : "centenarian";
// We can even return a string built using a template literal
return `${str0}${personExp}${str1}${ageStr}${str2}`;
}
const output = myTag`That ${person} is a ${age}.`;
console.log(output);
// That Mike is a youngster.
```
The tag does not have to be a plain identifier. You can use any expression with [precedence](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence#table) greater than 16, which includes [property access](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors), function call, [new expression](/en-US/docs/Web/JavaScript/Reference/Operators/new), or even another tagged template literal.
```js
console.log`Hello`; // [ 'Hello' ]
console.log.bind(1, 2)`Hello`; // 2 [ 'Hello' ]
new Function("console.log(arguments)")`Hello`; // [Arguments] { '0': [ 'Hello' ] }
function recursive(strings, ...values) {
console.log(strings, values);
return recursive;
}
recursive`Hello``World`;
// [ 'Hello' ] []
// [ 'World' ] []
```
While technically permitted by the syntax, _untagged_ template literals are strings and will throw a {{jsxref("TypeError")}} when chained.
```js
console.log(`Hello``World`); // TypeError: "Hello" is not a function
```
The only exception is optional chaining, which will throw a syntax error.
```js-nolint example-bad
console.log?.`Hello`; // SyntaxError: Invalid tagged template on optional chain
console?.log`Hello`; // SyntaxError: Invalid tagged template on optional chain
```
Note that these two expressions are still parsable. This means they would not be subject to [automatic semicolon insertion](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#automatic_semicolon_insertion), which will only insert semicolons to fix code that's otherwise unparsable.
```js-nolint example-bad
// Still a syntax error
const a = console?.log
`Hello`
```
Tag functions don't even need to return a string!
```js
function template(strings, ...keys) {
return (...values) => {
const dict = values[values.length - 1] || {};
const result = [strings[0]];
keys.forEach((key, i) => {
const value = Number.isInteger(key) ? values[key] : dict[key];
result.push(value, strings[i + 1]);
});
return result.join("");
};
}
const t1Closure = template`${0}${1}${0}!`;
// const t1Closure = template(["","","","!"],0,1,0);
t1Closure("Y", "A"); // "YAY!"
const t2Closure = template`${0} ${"foo"}!`;
// const t2Closure = template([""," ","!"],0,"foo");
t2Closure("Hello", { foo: "World" }); // "Hello World!"
const t3Closure = template`I'm ${"name"}. I'm almost ${"age"} years old.`;
// const t3Closure = template(["I'm ", ". I'm almost ", " years old."], "name", "age");
t3Closure("foo", { name: "MDN", age: 30 }); // "I'm MDN. I'm almost 30 years old."
t3Closure({ name: "MDN", age: 30 }); // "I'm MDN. I'm almost 30 years old."
```
The first argument received by the tag function is an array of strings. For any template literal, its length is equal to the number of substitutions (occurrences of `${β¦}`) plus one, and is therefore always non-empty.
For any particular tagged template literal expression, the tag function will always be called with the exact same literal array, no matter how many times the literal is evaluated.
```js
const callHistory = [];
function tag(strings, ...values) {
callHistory.push(strings);
// Return a freshly made object
return {};
}
function evaluateLiteral() {
return tag`Hello, ${"world"}!`;
}
console.log(evaluateLiteral() === evaluateLiteral()); // false; each time `tag` is called, it returns a new object
console.log(callHistory[0] === callHistory[1]); // true; all evaluations of the same tagged literal would pass in the same strings array
```
This allows the tag to cache the result based on the identity of its first argument. To further ensure the array value's stability, the first argument and its [`raw` property](#raw_strings) are both [frozen](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isFrozen), so you can't mutate them in any way.
### Raw strings
The special `raw` property, available on the first argument to the tag function, allows you to access the raw strings as they were entered, without processing [escape sequences](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#using_special_characters_in_strings).
```js
function tag(strings) {
console.log(strings.raw[0]);
}
tag`string text line 1 \n string text line 2`;
// Logs "string text line 1 \n string text line 2" ,
// including the two characters '\' and 'n'
```
In addition, the {{jsxref("String.raw()")}} method exists to create raw strings just like the default template function and string concatenation would create.
```js
const str = String.raw`Hi\n${2 + 3}!`;
// "Hi\\n5!"
str.length;
// 6
Array.from(str).join(",");
// "H,i,\\,n,5,!"
```
`String.raw` functions like an "identity" tag if the literal doesn't contain any escape sequences. In case you want an actual identity tag that always works as if the literal is untagged, you can make a custom function that passes the "cooked" (i.e. escape sequences are processed) literal array to `String.raw`, pretending they are raw strings.
```js
const identity = (strings, ...values) =>
String.raw({ raw: strings }, ...values);
console.log(identity`Hi\n${2 + 3}!`);
// Hi
// 5!
```
This is useful for many tools which give special treatment to literals tagged by a particular name.
```js
const html = (strings, ...values) => String.raw({ raw: strings }, ...values);
// Some formatters will format this literal's content as HTML
const doc = html`<!doctype html>
<html lang="en-US">
<head>
<title>Hello</title>
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>`;
```
### Tagged templates and escape sequences
In normal template literals, [the escape sequences in string literals](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#escape_sequences) are all allowed. Any other non-well-formed escape sequence is a syntax error. This includes:
- `\` followed by any decimal digit other than `0`, or `\0` followed by a decimal digit; for example `\9` and `\07` (which is a [deprecated syntax](/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#escape_sequences))
- `\x` followed by fewer than two hex digits (including none); for example `\xz`
- `\u` not followed by `{` and followed by fewer than four hex digits (including none); for example `\uz`
- `\u{}` enclosing an invalid Unicode code point β it contains a non-hex digit, or its value is greater than `10FFFF`; for example `\u{110000}` and `\u{z}`
> **Note:** `\` followed by other characters, while they may be useless since nothing is escaped, are not syntax errors.
However, this is problematic for tagged templates, which, in addition to the "cooked" literal, also have access to the raw literals (escape sequences are preserved as-is).
Tagged templates should allow the embedding of languages (for example [DSLs](https://en.wikipedia.org/wiki/Domain-specific_language), or [LaTeX](https://en.wikipedia.org/wiki/LaTeX)), where other escapes sequences are common. Therefore, the syntax restriction of well-formed escape sequences is removed from tagged templates.
```js
latex`\unicode`;
// Throws in older ECMAScript versions (ES2016 and earlier)
// SyntaxError: malformed Unicode character escape sequence
```
However, illegal escape sequences must still be represented in the "cooked" representation. They will show up as {{jsxref("undefined")}} element in the "cooked" array:
```js
function latex(str) {
return { cooked: str[0], raw: str.raw[0] };
}
latex`\unicode`;
// { cooked: undefined, raw: "\\unicode" }
```
Note that the escape-sequence restriction is only dropped from _tagged_ templates, but not from _untagged_ template literals:
```js-nolint example-bad
const bad = `bad escape sequence: \unicode`;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Text formatting](/en-US/docs/Web/JavaScript/Guide/Text_formatting) guide
- {{jsxref("String")}}
- {{jsxref("String.raw()")}}
- [Lexical grammar](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar)
- [ES6 in Depth: Template strings](https://hacks.mozilla.org/2015/05/es6-in-depth-template-strings-2/) on hacks.mozilla.org (2015)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference | data/mdn-content/files/en-us/web/javascript/reference/global_objects/index.md | ---
title: Standard built-in objects
slug: Web/JavaScript/Reference/Global_Objects
page-type: landing-page
---
{{jsSidebar("Objects")}}
This chapter documents all of JavaScript's standard, built-in objects, including their methods and properties.
The term "global objects" (or standard built-in objects) here is not to be confused with **the global object**. Here, "global objects" refer to **objects in the global scope**.
The **global object** itself can be accessed using the {{jsxref("Operators/this", "this")}} operator in the global scope. In fact, the global scope **consists of** the properties of the global object, including inherited properties, if any.
Other objects in the global scope are either [created by the user script](/en-US/docs/Web/JavaScript/Guide/Working_with_objects#creating_new_objects) or provided by the host application. The host objects available in browser contexts are documented in the [API reference](/en-US/docs/Web/API).
For more information about the distinction between the [DOM](/en-US/docs/Web/API/Document_Object_Model) and core [JavaScript](/en-US/docs/Web/JavaScript), see [JavaScript technologies overview](/en-US/docs/Web/JavaScript/JavaScript_technologies_overview).
## Standard objects by category
### Value properties
These global properties return a simple value. They have no properties or methods.
- {{jsxref("globalThis")}}
- {{jsxref("Infinity")}}
- {{jsxref("NaN")}}
- {{jsxref("undefined")}}
### Function properties
These global functionsβfunctions which are called globally, rather than on an objectβdirectly return their results to the caller.
- {{jsxref("Global_Objects/eval", "eval()")}}
- {{jsxref("isFinite()")}}
- {{jsxref("isNaN()")}}
- {{jsxref("parseFloat()")}}
- {{jsxref("parseInt()")}}
- {{jsxref("decodeURI()")}}
- {{jsxref("decodeURIComponent()")}}
- {{jsxref("encodeURI()")}}
- {{jsxref("encodeURIComponent()")}}
- {{jsxref("escape()")}} {{deprecated_inline}}
- {{jsxref("unescape()")}} {{deprecated_inline}}
### Fundamental objects
These objects represent fundamental language constructs.
- {{jsxref("Object")}}
- {{jsxref("Function")}}
- {{jsxref("Boolean")}}
- {{jsxref("Symbol")}}
### Error objects
Error objects are a special type of fundamental object. They include the basic {{jsxref("Error")}} type, as well as several specialized error types.
- {{jsxref("Error")}}
- {{jsxref("AggregateError")}}
- {{jsxref("EvalError")}}
- {{jsxref("RangeError")}}
- {{jsxref("ReferenceError")}}
- {{jsxref("SyntaxError")}}
- {{jsxref("TypeError")}}
- {{jsxref("URIError")}}
- {{jsxref("InternalError")}} {{non-standard_inline}}
### Numbers and dates
These are the base objects representing numbers, dates, and mathematical calculations.
- {{jsxref("Number")}}
- {{jsxref("BigInt")}}
- {{jsxref("Math")}}
- {{jsxref("Date")}}
### Text processing
These objects represent strings and support manipulating them.
- {{jsxref("String")}}
- {{jsxref("RegExp")}}
### Indexed collections
These objects represent collections of data which are ordered by an index value. This includes (typed) arrays and array-like constructs.
- {{jsxref("Array")}}
- {{jsxref("Int8Array")}}
- {{jsxref("Uint8Array")}}
- {{jsxref("Uint8ClampedArray")}}
- {{jsxref("Int16Array")}}
- {{jsxref("Uint16Array")}}
- {{jsxref("Int32Array")}}
- {{jsxref("Uint32Array")}}
- {{jsxref("BigInt64Array")}}
- {{jsxref("BigUint64Array")}}
- {{jsxref("Float32Array")}}
- {{jsxref("Float64Array")}}
### Keyed collections
These objects represent collections which use keys. The iterable collections ({{jsxref("Map")}} and {{jsxref("Set")}}) contain elements which are easily iterated in the order of insertion.
- {{jsxref("Map")}}
- {{jsxref("Set")}}
- {{jsxref("WeakMap")}}
- {{jsxref("WeakSet")}}
### Structured data
These objects represent and interact with structured data buffers and data coded using JavaScript Object Notation (JSON).
- {{jsxref("ArrayBuffer")}}
- {{jsxref("SharedArrayBuffer")}}
- {{jsxref("DataView")}}
- {{jsxref("Atomics")}}
- {{jsxref("JSON")}}
### Managing memory
These objects interact with the garbage collection mechanism.
- {{jsxref("WeakRef")}}
- {{jsxref("FinalizationRegistry")}}
### Control abstraction objects
Control abstractions can help to structure code, especially async code (without using deeply nested callbacks, for example).
- {{jsxref("Iterator")}}
- {{jsxref("AsyncIterator")}}
- {{jsxref("Promise")}}
- {{jsxref("GeneratorFunction")}}
- {{jsxref("AsyncGeneratorFunction")}}
- {{jsxref("Generator")}}
- {{jsxref("AsyncGenerator")}}
- {{jsxref("AsyncFunction")}}
### Reflection
- {{jsxref("Reflect")}}
- {{jsxref("Proxy")}}
### Internationalization
Additions to the ECMAScript core for language-sensitive functionalities.
- {{jsxref("Intl")}}
- {{jsxref("Intl.Collator")}}
- {{jsxref("Intl.DateTimeFormat")}}
- {{jsxref("Intl.DisplayNames")}}
- {{jsxref("Intl.DurationFormat")}}
- {{jsxref("Intl.ListFormat")}}
- {{jsxref("Intl.Locale")}}
- {{jsxref("Intl.NumberFormat")}}
- {{jsxref("Intl.PluralRules")}}
- {{jsxref("Intl.RelativeTimeFormat")}}
- {{jsxref("Intl.Segmenter")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/evalerror/index.md | ---
title: EvalError
slug: Web/JavaScript/Reference/Global_Objects/EvalError
page-type: javascript-class
browser-compat: javascript.builtins.EvalError
---
{{JSRef}}
The **`EvalError`** object indicates an error regarding the global {{jsxref("Global_Objects/eval", "eval()")}} function. This exception is not thrown by JavaScript anymore, however the `EvalError` object remains for compatibility.
`EvalError` is a {{Glossary("serializable object")}}, so it can be cloned with {{domxref("structuredClone()")}} or copied between [Workers](/en-US/docs/Web/API/Worker) using {{domxref("Worker/postMessage()", "postMessage()")}}.
`EvalError` is a subclass of {{jsxref("Error")}}.
## Constructor
- {{jsxref("EvalError/EvalError", "EvalError()")}}
- : Creates a new `EvalError` object.
## Instance properties
_Also inherits instance properties from its parent {{jsxref("Error")}}_.
These properties are defined on `EvalError.prototype` and shared by all `EvalError` instances.
- {{jsxref("Object/constructor", "EvalError.prototype.constructor")}}
- : The constructor function that created the instance object. For `EvalError` instances, the initial value is the {{jsxref("EvalError/EvalError", "EvalError")}} constructor.
- {{jsxref("Error/name", "EvalError.prototype.name")}}
- : Represents the name for the type of error. For `EvalError.prototype.name`, the initial value is `"EvalError"`.
## Instance methods
_Inherits instance methods from its parent {{jsxref("Error")}}_.
## Examples
### Creating an EvalError
```js
try {
throw new EvalError("Hello");
} catch (e) {
console.log(e instanceof EvalError); // true
console.log(e.message); // "Hello"
console.log(e.name); // "EvalError"
console.log(e.stack); // Stack of the error
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Error")}}
- {{jsxref("Global_Objects/eval", "eval()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/evalerror | data/mdn-content/files/en-us/web/javascript/reference/global_objects/evalerror/evalerror/index.md | ---
title: EvalError() constructor
slug: Web/JavaScript/Reference/Global_Objects/EvalError/EvalError
page-type: javascript-constructor
browser-compat: javascript.builtins.EvalError.EvalError
---
{{JSRef}}
The **`EvalError()`** constructor creates {{jsxref("EvalError")}} objects.
## Syntax
```js-nolint
new EvalError()
new EvalError(message)
new EvalError(message, options)
new EvalError(message, fileName)
new EvalError(message, fileName, lineNumber)
EvalError()
EvalError(message)
EvalError(message, options)
EvalError(message, fileName)
EvalError(message, fileName, lineNumber)
```
> **Note:** `EvalError()` can be called with or without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Both create a new `EvalError` instance.
### Parameters
- `message` {{optional_inline}}
- : Human-readable description of the error.
- `options` {{optional_inline}}
- : An object that has the following properties:
- `cause` {{optional_inline}}
- : A property indicating the specific cause of the error.
When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error.
- `fileName` {{optional_inline}} {{non-standard_inline}}
- : The name of the file containing the code that caused the exception
- `lineNumber` {{optional_inline}} {{non-standard_inline}}
- : The line number of the code that caused the exception
## Examples
`EvalError` is not used in the current ECMAScript specification and will
thus not be thrown by the runtime. However, the object itself remains for backwards
compatibility with earlier versions of the specification.
### Creating an EvalError
```js
try {
throw new EvalError("Hello");
} catch (e) {
console.log(e instanceof EvalError); // true
console.log(e.message); // "Hello"
console.log(e.name); // "EvalError"
console.log(e.stack); // Stack of the error
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Error")}}
- {{jsxref("Global_Objects/eval", "eval()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/uint8array/index.md | ---
title: Uint8Array
slug: Web/JavaScript/Reference/Global_Objects/Uint8Array
page-type: javascript-class
browser-compat: javascript.builtins.Uint8Array
---
{{JSRef}}
The **`Uint8Array`** typed array represents an array of 8-bit unsigned integers. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
`Uint8Array` is a subclass of the hidden {{jsxref("TypedArray")}} class.
## Constructor
- {{jsxref("Uint8Array/Uint8Array", "Uint8Array()")}}
- : Creates a new `Uint8Array` object.
## Static properties
_Also inherits static properties from its parent {{jsxref("TypedArray")}}_.
- {{jsxref("TypedArray/BYTES_PER_ELEMENT", "Uint8Array.BYTES_PER_ELEMENT")}}
- : Returns a number value of the element size. `1` in the case of `Uint8Array`.
## Static methods
_Inherits static methods from its parent {{jsxref("TypedArray")}}_.
## Instance properties
_Also inherits instance properties from its parent {{jsxref("TypedArray")}}_.
These properties are defined on `Uint8Array.prototype` and shared by all `Uint8Array` instances.
- {{jsxref("TypedArray/BYTES_PER_ELEMENT", "Uint8Array.prototype.BYTES_PER_ELEMENT")}}
- : Returns a number value of the element size. `1` in the case of a `Uint8Array`.
- {{jsxref("Object/constructor", "Uint8Array.prototype.constructor")}}
- : The constructor function that created the instance object. For `Uint8Array` instances, the initial value is the {{jsxref("Uint8Array/Uint8Array", "Uint8Array")}} constructor.
## Instance methods
_Inherits instance methods from its parent {{jsxref("TypedArray")}}_.
## Examples
### Different ways to create a Uint8Array
```js
// From a length
const uint8 = new Uint8Array(2);
uint8[0] = 42;
console.log(uint8[0]); // 42
console.log(uint8.length); // 2
console.log(uint8.BYTES_PER_ELEMENT); // 1
// From an array
const x = new Uint8Array([21, 31]);
console.log(x[1]); // 31
// From another TypedArray
const y = new Uint8Array(x);
console.log(y[0]); // 21
// From an ArrayBuffer
const buffer = new ArrayBuffer(8);
const z = new Uint8Array(buffer, 1, 4);
console.log(z.byteOffset); // 1
// From an iterable
const iterable = (function* () {
yield* [1, 2, 3];
})();
const uint8FromIterable = new Uint8Array(iterable);
console.log(uint8FromIterable);
// Uint8Array [1, 2, 3]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Uint8Array` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("TypedArray")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("DataView")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/uint8array | data/mdn-content/files/en-us/web/javascript/reference/global_objects/uint8array/uint8array/index.md | ---
title: Uint8Array() constructor
slug: Web/JavaScript/Reference/Global_Objects/Uint8Array/Uint8Array
page-type: javascript-constructor
browser-compat: javascript.builtins.Uint8Array.Uint8Array
---
{{JSRef}}
The **`Uint8Array()`** constructor creates {{jsxref("Uint8Array")}} objects. The contents are initialized to `0`.
## Syntax
```js-nolint
new Uint8Array()
new Uint8Array(length)
new Uint8Array(typedArray)
new Uint8Array(object)
new Uint8Array(buffer)
new Uint8Array(buffer, byteOffset)
new Uint8Array(buffer, byteOffset, length)
```
> **Note:** `Uint8Array()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}.
### Parameters
See [`TypedArray`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters).
### Exceptions
See [`TypedArray`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions).
## Examples
### Different ways to create a Uint8Array
```js
// From a length
const uint8 = new Uint8Array(2);
uint8[0] = 42;
console.log(uint8[0]); // 42
console.log(uint8.length); // 2
console.log(uint8.BYTES_PER_ELEMENT); // 1
// From an array
const x = new Uint8Array([21, 31]);
console.log(x[1]); // 31
// From another TypedArray
const y = new Uint8Array(x);
console.log(y[0]); // 21
// From an ArrayBuffer
const buffer = new ArrayBuffer(8);
const z = new Uint8Array(buffer, 1, 4);
console.log(z.byteOffset); // 1
// From an iterable
const iterable = (function* () {
yield* [1, 2, 3];
})();
const uint8FromIterable = new Uint8Array(iterable);
console.log(uint8FromIterable);
// Uint8Array [1, 2, 3]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Uint8Array` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("TypedArray")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("DataView")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/json/index.md | ---
title: JSON
slug: Web/JavaScript/Reference/Global_Objects/JSON
page-type: javascript-namespace
browser-compat: javascript.builtins.JSON
---
{{JSRef}}
The **`JSON`** namespace object contains static methods for parsing values from and converting values to [JavaScript Object Notation](https://json.org/) ({{Glossary("JSON")}}).
## Description
Unlike most global objects, `JSON` is not a constructor. You cannot use it with the [`new` operator](/en-US/docs/Web/JavaScript/Reference/Operators/new) or invoke the `JSON` object as a function. All properties and methods of `JSON` are static (just like the {{jsxref("Math")}} object).
### JavaScript and JSON differences
JSON is a syntax for serializing objects, arrays, numbers, strings, booleans, and [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null). It is based upon JavaScript syntax, but is distinct from JavaScript: most of JavaScript is _not_ JSON. For example:
- Objects and Arrays
- : Property names must be double-quoted strings; [trailing commas](/en-US/docs/Web/JavaScript/Reference/Trailing_commas) are forbidden.
- Numbers
- : Leading zeros are prohibited. A decimal point must be followed by at least one digit. `NaN` and `Infinity` are unsupported.
Any JSON text is a valid JavaScript expression, but only after the [JSON superset](https://github.com/tc39/proposal-json-superset) revision. Before the revision, U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are allowed in string literals and property keys in JSON; but the same use in JavaScript string literals is a {{jsxref("SyntaxError")}}.
Other differences include allowing only double-quoted strings and no support for {{jsxref("undefined")}} or comments. For those who wish to use a more human-friendly configuration format based on JSON, there is [JSON5](https://json5.org/), used by the Babel compiler, and the more commonly used [YAML](https://en.wikipedia.org/wiki/YAML).
The same text may represent different values in JavaScript object literals vs. JSON as well. For more information, see [Object literal syntax vs. JSON](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#object_literal_syntax_vs._json).
### Full JSON grammar
Valid JSON syntax is formally defined by the following grammar, expressed in [ABNF](https://en.wikipedia.org/wiki/Augmented_Backus%E2%80%93Naur_form), and copied from [IETF JSON standard (RFC)](https://datatracker.ietf.org/doc/html/rfc8259):
```plain
JSON-text = object / array
begin-array = ws %x5B ws ; [ left square bracket
begin-object = ws %x7B ws ; { left curly bracket
end-array = ws %x5D ws ; ] right square bracket
end-object = ws %x7D ws ; } right curly bracket
name-separator = ws %x3A ws ; : colon
value-separator = ws %x2C ws ; , comma
ws = *(
%x20 / ; Space
%x09 / ; Horizontal tab
%x0A / ; Line feed or New line
%x0D ; Carriage return
)
value = false / null / true / object / array / number / string
false = %x66.61.6c.73.65 ; false
null = %x6e.75.6c.6c ; null
true = %x74.72.75.65 ; true
object = begin-object [ member *( value-separator member ) ]
end-object
member = string name-separator value
array = begin-array [ value *( value-separator value ) ] end-array
number = [ minus ] int [ frac ] [ exp ]
decimal-point = %x2E ; .
digit1-9 = %x31-39 ; 1-9
e = %x65 / %x45 ; e E
exp = e [ minus / plus ] 1*DIGIT
frac = decimal-point 1*DIGIT
int = zero / ( digit1-9 *DIGIT )
minus = %x2D ; -
plus = %x2B ; +
zero = %x30 ; 0
string = quotation-mark *char quotation-mark
char = unescaped /
escape (
%x22 / ; " quotation mark U+0022
%x5C / ; \ reverse solidus U+005C
%x2F / ; / solidus U+002F
%x62 / ; b backspace U+0008
%x66 / ; f form feed U+000C
%x6E / ; n line feed U+000A
%x72 / ; r carriage return U+000D
%x74 / ; t tab U+0009
%x75 4HEXDIG ) ; uXXXX U+XXXX
escape = %x5C ; \
quotation-mark = %x22 ; "
unescaped = %x20-21 / %x23-5B / %x5D-10FFFF
HEXDIG = DIGIT / %x41-46 / %x61-66 ; 0-9, A-F, or a-f
; HEXDIG equivalent to HEXDIG rule in [RFC5234]
DIGIT = %x30-39 ; 0-9
; DIGIT equivalent to DIGIT rule in [RFC5234]
```
Insignificant {{Glossary("whitespace")}} may be present anywhere except within a `JSONNumber` (numbers must contain no whitespace) or `JSONString` (where it is interpreted as the corresponding character in the string, or would cause an error). The tab character ([U+0009](https://unicode-table.com/en/0009/)), carriage return ([U+000D](https://unicode-table.com/en/000D/)), line feed ([U+000A](https://unicode-table.com/en/000A/)), and space ([U+0020](https://unicode-table.com/en/0020/)) characters are the only valid whitespace characters.
## Static properties
- `JSON[@@toStringTag]`
- : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"JSON"`. This property is used in {{jsxref("Object.prototype.toString()")}}.
## Static methods
- {{jsxref("JSON.parse()")}}
- : Parse a piece of string text as JSON, optionally transforming the produced value and its properties, and return the value.
- {{jsxref("JSON.stringify()")}}
- : Return a JSON string corresponding to the specified value, optionally including only certain properties or replacing property values in a user-defined manner.
## Examples
### Example JSON
```json
{
"browsers": {
"firefox": {
"name": "Firefox",
"pref_url": "about:config",
"releases": {
"1": {
"release_date": "2004-11-09",
"status": "retired",
"engine": "Gecko",
"engine_version": "1.7"
}
}
}
}
}
```
You can use the {{jsxref("JSON.parse()")}} method to convert the above JSON string into a JavaScript object:
```js
const jsonText = `{
"browsers": {
"firefox": {
"name": "Firefox",
"pref_url": "about:config",
"releases": {
"1": {
"release_date": "2004-11-09",
"status": "retired",
"engine": "Gecko",
"engine_version": "1.7"
}
}
}
}
}`;
console.log(JSON.parse(jsonText));
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.toJSON()")}}
- [JSON Diff](https://json-diff.com/)
- [JSON Beautifier/editor](https://jsonbeautifier.org/)
- [JSON Parser](https://jsonparser.org/)
- [JSON Validator](https://tools.learningcontainer.com/json-validator/)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/json | data/mdn-content/files/en-us/web/javascript/reference/global_objects/json/parse/index.md | ---
title: JSON.parse()
slug: Web/JavaScript/Reference/Global_Objects/JSON/parse
page-type: javascript-static-method
browser-compat: javascript.builtins.JSON.parse
---
{{JSRef}}
The **`JSON.parse()`** static method parses a JSON string, constructing the JavaScript value or object described by the string. An optional _reviver_ function can be provided to perform a transformation on the resulting object before it is returned.
{{EmbedInteractiveExample("pages/js/json-parse.html")}}
## Syntax
```js-nolint
JSON.parse(text)
JSON.parse(text, reviver)
```
### Parameters
- `text`
- : The string to parse as JSON. See the {{jsxref("JSON")}} object for a description of JSON syntax.
- `reviver` {{optional_inline}}
- : If a function, this prescribes how each value originally produced by parsing is transformed before being returned. Non-callable values are ignored. The function is called with the following arguments:
- `key`
- : The key associated with the value.
- `value`
- : The value produced by parsing.
### Return value
The {{jsxref("Object")}}, {{jsxref("Array")}}, string, number, boolean, or `null` value corresponding to the given JSON `text`.
### Exceptions
- {{jsxref("SyntaxError")}}
- : Thrown if the string to parse is not valid JSON.
## Description
`JSON.parse()` parses a JSON string according to the [JSON grammar](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON#full_json_grammar), then evaluates the string as if it's a JavaScript expression. The only instance where a piece of JSON text represents a different value from the same JavaScript expression is when dealing with the `"__proto__"` key β see [Object literal syntax vs. JSON](/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#object_literal_syntax_vs._json).
### The reviver parameter
If a `reviver` is specified, the value computed by parsing is _transformed_ before being returned. Specifically, the computed value and all its properties (in a [depth-first](https://en.wikipedia.org/wiki/Depth-first_search) fashion, beginning with the most nested properties and proceeding to the original value itself) are individually run through the `reviver`.
The `reviver` is called with the object containing the property being processed as `this` (unless you define the `reviver` as an arrow function, in which case there's no separate `this` binding) and two arguments: `key` and `value`, representing the property name as a string (even for arrays) and the property value. If the `reviver` function returns {{jsxref("undefined")}} (or returns no value β for example, if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value. If the `reviver` only transforms some values and not others, be certain to return all untransformed values as-is β otherwise, they will be deleted from the resulting object.
Similar to the `replacer` parameter of {{jsxref("JSON.stringify()")}}, for arrays and objects, `reviver` will be last called on the root value with an empty string as the `key` and the root object as the `value`. For other valid JSON values, `reviver` works similarly and is called once with an empty string as the `key` and the value itself as the `value`.
If you return another value from `reviver`, that value will completely replace the originally parsed value. This even applies to the root value. For example:
```js
const transformedObj1 = JSON.parse('[1,5,{"s":1}]', (key, value) => {
return typeof value === "object" ? undefined : value;
});
console.log(transformedObj1); // undefined
```
There is no way to work around this generically. You cannot specially handle the case where `key` is an empty string, because JSON objects can also contain keys that are empty strings. You need to know very precisely what kind of transformation is needed for each key when implementing the reviver.
Note that `reviver` is run after the value is parsed. So, for example, numbers in JSON text will have already been converted to JavaScript numbers, and may lose precision in the process. To transfer large numbers without loss of precision, serialize them as strings, and revive them to [BigInts](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt), or other appropriate arbitrary precision formats.
## Examples
### Using JSON.parse()
```js
JSON.parse("{}"); // {}
JSON.parse("true"); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse("null"); // null
```
### Using the reviver parameter
```js
JSON.parse(
'{"p": 5}',
(key, value) =>
typeof value === "number"
? value * 2 // return value * 2 for numbers
: value, // return everything else unchanged
);
// { p: 10 }
JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', (key, value) => {
console.log(key);
return value;
});
// 1
// 2
// 4
// 6
// 5
// 3
// ""
```
### Using reviver when paired with the replacer of JSON.stringify()
In order for a value to properly round-trip (that is, it gets deserialized to the same original object), the serialization process must preserve the type information. For example, you can use the `replacer` parameter of {{jsxref("JSON.stringify()")}} for this purpose:
```js
// Maps are normally serialized as objects with no properties.
// We can use the replacer to specify the entries to be serialized.
const map = new Map([
[1, "one"],
[2, "two"],
[3, "three"],
]);
const jsonText = JSON.stringify(map, (key, value) =>
value instanceof Map ? Array.from(value.entries()) : value,
);
console.log(jsonText);
// [[1,"one"],[2,"two"],[3,"three"]]
const map2 = JSON.parse(jsonText, (key, value) =>
Array.isArray(value) ? new Map(value) : value,
);
console.log(map2);
// Map { 1 => "one", 2 => "two", 3 => "three" }
```
Because JSON has no syntax space for annotating type metadata, in order to revive values that are not plain objects, you have to consider one of the following:
- Serialize the entire object to a string and prefix it with a type tag.
- "Guess" based on the structure of the data (for example, an array of two-member arrays)
- If the shape of the payload is fixed, based on the property name (for example, all properties called `registry` hold `Map` objects).
### JSON.parse() does not allow trailing commas
```js example-bad
// both will throw a SyntaxError
JSON.parse("[1, 2, 3, 4, ]");
JSON.parse('{"foo" : 1, }');
```
### JSON.parse() does not allow single quotes
```js example-bad
// will throw a SyntaxError
JSON.parse("{'foo': 1}");
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("JSON.stringify()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/json | data/mdn-content/files/en-us/web/javascript/reference/global_objects/json/stringify/index.md | ---
title: JSON.stringify()
slug: Web/JavaScript/Reference/Global_Objects/JSON/stringify
page-type: javascript-static-method
browser-compat: javascript.builtins.JSON.stringify
---
{{JSRef}}
The **`JSON.stringify()`** static method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
{{EmbedInteractiveExample("pages/js/json-stringify.html", "taller")}}
## Syntax
```js-nolint
JSON.stringify(value)
JSON.stringify(value, replacer)
JSON.stringify(value, replacer, space)
```
### Parameters
- `value`
- : The value to convert to a JSON string.
- `replacer` {{optional_inline}}
- : A function that alters the behavior of the stringification process, or an array of strings and numbers that specifies properties of `value` to be included in the output. If `replacer` is an array, all elements in this array that are not strings or numbers (either primitives or wrapper objects), including {{jsxref("Symbol")}} values, are completely ignored. If `replacer` is anything other than a function or an array (e.g. [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) or not provided), all string-keyed properties of the object are included in the resulting JSON string.
- `space` {{optional_inline}}
- : A string or number that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes.
If this is a number, it indicates the number of space characters to be used as indentation, clamped to 10 (that is, any number greater than `10` is treated as if it were `10`). Values less than 1 indicate that no space should be used.
If this is a string, the string (or the first 10 characters of the string, if it's longer than that) is inserted before every nested object or array.
If `space` is anything other than a string or number (can be either a primitive or a wrapper object) β for example, is [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) or not provided β no white space is used.
### Return value
A JSON string representing the given value, or undefined.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown in one of the following cases:
- `value` contains a circular reference.
- A {{jsxref("BigInt")}} value is encountered.
## Description
`JSON.stringify()` converts a value to the JSON notation that the value represents. Values are stringified in the following manner:
- {{jsxref("Boolean")}}, {{jsxref("Number")}}, {{jsxref("String")}}, and {{jsxref("BigInt")}} (obtainable via [`Object()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) objects are converted to the corresponding primitive values during stringification, in accordance with the traditional conversion semantics. {{jsxref("Symbol")}} objects (obtainable via [`Object()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)) are treated as plain objects.
- Attempting to serialize {{jsxref("BigInt")}} values will throw. However, if the BigInt has a `toJSON()` method (through monkey patching: `BigInt.prototype.toJSON = ...`), that method can provide the serialization result. This constraint ensures that a proper serialization (and, very likely, its accompanying deserialization) behavior is always explicitly provided by the user.
- {{jsxref("undefined")}}, {{jsxref("Function")}}, and {{jsxref("Symbol")}} values are not valid JSON values. If any such values are encountered during conversion, they are either omitted (when found in an object) or changed to [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) (when found in an array). `JSON.stringify()` can return `undefined` when passing in "pure" values like `JSON.stringify(() => {})` or `JSON.stringify(undefined)`.
- The numbers {{jsxref("Infinity")}} and {{jsxref("NaN")}}, as well as the value [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null), are all considered `null`. (But unlike the values in the previous point, they would never be omitted.)
- Arrays are serialized as arrays (enclosed by square brackets). Only array indices between 0 and `length - 1` (inclusive) are serialized; other properties are ignored.
- For other objects:
- All {{jsxref("Symbol")}}-keyed properties will be completely ignored, even when using the [`replacer`](#the_replacer_parameter) parameter.
- If the value has a `toJSON()` method, it's responsible to define what data will be serialized. Instead of the object being serialized, the value returned by the `toJSON()` method when called will be serialized. `JSON.stringify()` calls `toJSON` with one parameter, the `key`, which has the same semantic as the `key` parameter of the [`replacer`](#the_replacer_parameter) function:
- if this object is a property value, the property name
- if it is in an array, the index in the array, as a string
- if `JSON.stringify()` was directly called on this object, an empty string
{{jsxref("Date")}} objects implement the [`toJSON()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON) method which returns a string (the same as [`date.toISOString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)). Thus, they will be stringified as strings.
- Only [enumerable own properties](/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) are visited. This means {{jsxref("Map")}}, {{jsxref("Set")}}, etc. will become `"{}"`. You can use the [`replacer`](#the_replacer_parameter) parameter to serialize them to something more useful.
Properties are visited using the same algorithm as [`Object.keys()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), which has a well-defined order and is stable across implementations. For example, `JSON.stringify` on the same object will always produce the same string, and `JSON.parse(JSON.stringify(obj))` would produce an object with the same key ordering as the original (assuming the object is completely JSON-serializable).
### The replacer parameter
The `replacer` parameter can be either a function or an array.
As an array, its elements indicate the names of the properties in the object that should be included in the resulting JSON string. Only string and number values are taken into account; symbol keys are ignored.
As a function, it takes two parameters: the `key` and the `value` being stringified. The object in which the key was found is provided as the `replacer`'s `this` context.
The `replacer` function is called for the initial object being stringified as well, in which case the `key` is an empty string (`""`). It is then called for each property on the object or array being stringified. Array indices will be provided in its string form as `key`. The current property value will be replaced with the `replacer`'s return value for stringification. This means:
- If you return a number, string, boolean, or `null`, that value is directly serialized and used as the property's value. (Returning a BigInt will throw as well.)
- If you return a {{jsxref("Function")}}, {{jsxref("Symbol")}}, or {{jsxref("undefined")}}, the property is not included in the output.
- If you return any other object, the object is recursively stringified, calling the `replacer` function on each property.
> **Note:** When parsing JSON generated with `replacer` functions, you would likely want to use the [`reviver`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_the_reviver_parameter) parameter to perform the reverse operation.
Typically, array elements' index would never shift (even when the element is an invalid value like a function, it will become `null` instead of omitted). Using the `replacer` function allows you to control the order of the array elements by returning a different array.
### The space parameter
The `space` parameter may be used to control spacing in the final string.
- If it is a number, successive levels in the stringification will each be indented by this many space characters.
- If it is a string, successive levels will be indented by this string.
Each level of indentation will never be longer than 10. Number values of `space` are clamped to 10, and string values are truncated to 10 characters.
## Examples
### Using JSON.stringify
```js
JSON.stringify({}); // '{}'
JSON.stringify(true); // 'true'
JSON.stringify("foo"); // '"foo"'
JSON.stringify([1, "false", false]); // '[1,"false",false]'
JSON.stringify([NaN, null, Infinity]); // '[null,null,null]'
JSON.stringify({ x: 5 }); // '{"x":5}'
JSON.stringify(new Date(1906, 0, 2, 15, 4, 5));
// '"1906-01-02T15:04:05.000Z"'
JSON.stringify({ x: 5, y: 6 });
// '{"x":5,"y":6}'
JSON.stringify([new Number(3), new String("false"), new Boolean(false)]);
// '[3,"false",false]'
// String-keyed array elements are not enumerable and make no sense in JSON
const a = ["foo", "bar"];
a["baz"] = "quux"; // a: [ 0: 'foo', 1: 'bar', baz: 'quux' ]
JSON.stringify(a);
// '["foo","bar"]'
JSON.stringify({ x: [10, undefined, function () {}, Symbol("")] });
// '{"x":[10,null,null,null]}'
// Standard data structures
JSON.stringify([
new Set([1]),
new Map([[1, 2]]),
new WeakSet([{ a: 1 }]),
new WeakMap([[{ a: 1 }, 2]]),
]);
// '[{},{},{},{}]'
// TypedArray
JSON.stringify([new Int8Array([1]), new Int16Array([1]), new Int32Array([1])]);
// '[{"0":1},{"0":1},{"0":1}]'
JSON.stringify([
new Uint8Array([1]),
new Uint8ClampedArray([1]),
new Uint16Array([1]),
new Uint32Array([1]),
]);
// '[{"0":1},{"0":1},{"0":1},{"0":1}]'
JSON.stringify([new Float32Array([1]), new Float64Array([1])]);
// '[{"0":1},{"0":1}]'
// toJSON()
JSON.stringify({
x: 5,
y: 6,
toJSON() {
return this.x + this.y;
},
});
// '11'
// Symbols:
JSON.stringify({ x: undefined, y: Object, z: Symbol("") });
// '{}'
JSON.stringify({ [Symbol("foo")]: "foo" });
// '{}'
JSON.stringify({ [Symbol.for("foo")]: "foo" }, [Symbol.for("foo")]);
// '{}'
JSON.stringify({ [Symbol.for("foo")]: "foo" }, (k, v) => {
if (typeof k === "symbol") {
return "a symbol";
}
});
// undefined
// Non-enumerable properties:
JSON.stringify(
Object.create(null, {
x: { value: "x", enumerable: false },
y: { value: "y", enumerable: true },
}),
);
// '{"y":"y"}'
// BigInt values throw
JSON.stringify({ x: 2n });
// TypeError: BigInt value can't be serialized in JSON
```
### Using a function as replacer
```js
function replacer(key, value) {
// Filtering out properties
if (typeof value === "string") {
return undefined;
}
return value;
}
const foo = {
foundation: "Mozilla",
model: "box",
week: 45,
transport: "car",
month: 7,
};
JSON.stringify(foo, replacer);
// '{"week":45,"month":7}'
```
If you wish the `replacer` to distinguish an initial object from a key with an empty string property (since both would give the empty string as key and potentially an object as value), you will have to keep track of the iteration count (if it is beyond the first iteration, it is a genuine empty string key).
```js
function makeReplacer() {
let isInitial = true;
return (key, value) => {
if (isInitial) {
isInitial = false;
return value;
}
if (key === "") {
// Omit all properties with name "" (except the initial object)
return undefined;
}
return value;
};
}
const replacer = makeReplacer();
console.log(JSON.stringify({ "": 1, b: 2 }, replacer)); // "{"b":2}"
```
### Using an array as replacer
```js
const foo = {
foundation: "Mozilla",
model: "box",
week: 45,
transport: "car",
month: 7,
};
JSON.stringify(foo, ["week", "month"]);
// '{"week":45,"month":7}', only keep "week" and "month" properties
```
### Using the space parameter
Indent the output with one space:
```js
console.log(JSON.stringify({ a: 2 }, null, " "));
/*
{
"a": 2
}
*/
```
Using a tab character mimics standard pretty-print appearance:
<!-- markdownlint-disable MD010 -->
```js
console.log(JSON.stringify({ uno: 1, dos: 2 }, null, "\t"));
/*
{
"uno": 1,
"dos": 2
}
*/
```
<!-- markdownlint-enable MD010 -->
### toJSON() behavior
Defining `toJSON()` for an object allows overriding its serialization behavior.
```js
const obj = {
data: "data",
toJSON(key) {
return key ? `Now I am a nested object under key '${key}'` : this;
},
};
JSON.stringify(obj);
// '{"data":"data"}'
JSON.stringify({ obj });
// '{"obj":"Now I am a nested object under key 'obj'"}'
JSON.stringify([obj]);
// '["Now I am a nested object under key '0'"]'
```
### Issue with serializing circular references
Since the [JSON format](https://www.json.org/) doesn't support object references (although an [IETF draft exists](https://datatracker.ietf.org/doc/html/draft-pbryan-zyp-json-ref-03)), a {{jsxref("TypeError")}} will be thrown if one attempts to encode an object with circular references.
```js example-bad
const circularReference = {};
circularReference.myself = circularReference;
// Serializing circular references throws "TypeError: cyclic object value"
JSON.stringify(circularReference);
```
To serialize circular references, you can use a library that supports them (e.g. [cycle.js](https://github.com/douglascrockford/JSON-js/blob/master/cycle.js) by Douglas Crockford) or implement a solution yourself, which will require finding and replacing (or removing) the cyclic references by serializable values.
If you are using `JSON.stringify()` to deep-copy an object, you may instead want to use [`structuredClone()`](/en-US/docs/Web/API/structuredClone), which supports circular references. JavaScript engine APIs for binary serialization, such as [`v8.serialize()`](https://nodejs.org/api/v8.html#v8serializevalue), also support circular references.
### Using JSON.stringify() with localStorage
In a case where you want to store an object created by your user and allow it to be restored even after the browser has been closed, the following example is a model for the applicability of `JSON.stringify()`:
```js
// Creating an example of JSON
const session = {
screens: [],
state: true,
};
session.screens.push({ name: "screenA", width: 450, height: 250 });
session.screens.push({ name: "screenB", width: 650, height: 350 });
session.screens.push({ name: "screenC", width: 750, height: 120 });
session.screens.push({ name: "screenD", width: 250, height: 60 });
session.screens.push({ name: "screenE", width: 390, height: 120 });
session.screens.push({ name: "screenF", width: 1240, height: 650 });
// Converting the JSON string with JSON.stringify()
// then saving with localStorage in the name of session
localStorage.setItem("session", JSON.stringify(session));
// Example of how to transform the String generated through
// JSON.stringify() and saved in localStorage in JSON object again
const restoredSession = JSON.parse(localStorage.getItem("session"));
// Now restoredSession variable contains the object that was saved
// in localStorage
console.log(restoredSession);
```
### Well-formed JSON.stringify()
Engines implementing the [well-formed JSON.stringify specification](https://github.com/tc39/proposal-well-formed-stringify) will stringify lone surrogates (any code point from U+D800 to U+DFFF) using Unicode escape sequences rather than literally (outputting lone surrogates). Before this change, such strings could not be encoded in valid UTF-8 or UTF-16:
```js
JSON.stringify("\uD800"); // '"οΏ½"'
```
But with this change `JSON.stringify()` represents lone surrogates using JSON escape sequences that _can_ be encoded in valid UTF-8 or UTF-16:
```js
JSON.stringify("\uD800"); // '"\\ud800"'
```
This change should be backwards-compatible as long as you pass the result of `JSON.stringify()` to APIs such as `JSON.parse()` that will accept any valid JSON text, because they will treat Unicode escapes of lone surrogates as identical to the lone surrogates themselves. _Only_ if you are directly interpreting the result of `JSON.stringify()` do you need to carefully handle `JSON.stringify()`'s two possible encodings of these code points.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of modern `JSON.stringify` behavior (symbol and well-formed unicode) in `core-js`](https://github.com/zloirock/core-js#ecmascript-json)
- {{jsxref("JSON.parse()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/undefined/index.md | ---
title: undefined
slug: Web/JavaScript/Reference/Global_Objects/undefined
page-type: javascript-global-property
browser-compat: javascript.builtins.undefined
---
{{jsSidebar("Objects")}}
The **`undefined`** global property represents the primitive
value [`undefined`](/en-US/docs/Web/JavaScript/Data_structures#undefined_type). It is one of JavaScript's
{{Glossary("Primitive", "primitive types")}}.
{{EmbedInteractiveExample("pages/js/globalprops-undefined.html")}}
## Value
The primitive value [`undefined`](/en-US/docs/Web/JavaScript/Data_structures#undefined_type).
{{js_property_attributes(0, 0, 0)}}
## Description
`undefined` is a property of the _global object_. That is, it is a variable in global scope.
In all non-legacy browsers, `undefined` is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it.
A variable that has not been assigned a value is of type `undefined`. A
method or statement also returns `undefined` if the variable that is being
evaluated does not have an assigned value. A function returns `undefined` if
a value was not {{jsxref("Statements/return", "returned")}}.
> **Note:** While you can use `undefined` as an {{Glossary("identifier")}} (variable name) in any scope other than the global scope (because `undefined` is not a [reserved word](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#reserved_words)), doing so is a very bad idea that will make your code difficult to maintain and debug.
>
> ```js example-bad
> // DON'T DO THIS
>
> (() => {
> const undefined = "foo";
> console.log(undefined, typeof undefined); // foo string
> })();
>
> ((undefined) => {
> console.log(undefined, typeof undefined); // foo string
> })("foo");
> ```
## Examples
### Strict equality and undefined
You can use `undefined` and the strict equality and inequality operators to
determine whether a variable has a value. In the following code, the variable
`x` is not initialized, and the `if` statement evaluates to true.
```js
let x;
if (x === undefined) {
// these statements execute
} else {
// these statements do not execute
}
```
> **Note:** The _strict equality_ operator (as opposed to the
> _standard equality_ operator) must be used here, because
> `x == undefined` also checks whether `x` is `null`,
> while strict equality doesn't. This is because `null` is not equivalent to
> `undefined`.
>
> See [Equality comparison and sameness](/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness) for details.
### typeof operator and undefined
Alternatively, {{jsxref("Operators/typeof", "typeof")}} can be used:
```js
let x;
if (typeof x === "undefined") {
// these statements execute
}
```
One reason to use {{jsxref("Operators/typeof", "typeof")}} is that it does not throw an
error if the variable has not been declared.
```js
// x has not been declared before
// evaluates to true without errors
if (typeof x === "undefined") {
// these statements execute
}
// Throws a ReferenceError
if (x === undefined) {
}
```
However, there is another alternative. JavaScript is a statically scoped language, so
knowing if a variable is declared can be read by seeing whether it is declared in an
enclosing context.
The global scope is bound to the {{jsxref("globalThis", "global object", "", 1)}}, so
checking the existence of a variable in the global context can be done by checking the
existence of a property on the _global object_, using the
{{jsxref("Operators/in", "in")}} operator, for instance:
```js
if ("x" in window) {
// These statements execute only if x is defined globally
}
```
### void operator and undefined
The {{jsxref("Operators/void", "void")}} operator is a third alternative.
```js
let x;
if (x === void 0) {
// these statements execute
}
// y has not been declared before
if (y === void 0) {
// throws Uncaught ReferenceError: y is not defined
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [JavaScript data types and data structures](/en-US/docs/Web/JavaScript/Data_structures)
- [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakset/index.md | ---
title: WeakSet
slug: Web/JavaScript/Reference/Global_Objects/WeakSet
page-type: javascript-class
browser-compat: javascript.builtins.WeakSet
---
{{JSRef}}
A **`WeakSet`** is a collection of garbage-collectable values, including objects and [non-registered symbols](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry). A value in the `WeakSet` may only occur once. It is unique in the `WeakSet`'s collection.
## Description
Values of WeakSets must be garbage-collectable. Most {{Glossary("Primitive", "primitive data types")}} can be arbitrarily created and don't have a lifetime, so they cannot be stored. Objects and [non-registered symbols](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) can be stored because they are garbage-collectable.
The main differences to the {{jsxref("Set")}} object are:
- `WeakSet`s are collections of **objects and symbols only**. They cannot contain arbitrary values of any type, as {{jsxref("Set")}}s can.
- The `WeakSet` is _weak_, meaning references to objects in a `WeakSet` are held _weakly_. If no other references to a value stored in the `WeakSet` exist, those values can be garbage collected.
> **Note:** This also means that there is no list of current values stored in the collection. `WeakSets` are not enumerable.
### Use case: Detecting circular references
Functions that call themselves recursively need a way of guarding against circular data structures by tracking which objects have already been processed.
`WeakSet`s are ideal for this purpose:
```js
// Execute a callback on everything stored inside an object
function execRecursively(fn, subject, _refs = new WeakSet()) {
// Avoid infinite recursion
if (_refs.has(subject)) {
return;
}
fn(subject);
if (typeof subject === "object" && subject) {
_refs.add(subject);
for (const key in subject) {
execRecursively(fn, subject[key], _refs);
}
_refs.delete(subject);
}
}
const foo = {
foo: "Foo",
bar: {
bar: "Bar",
},
};
foo.bar.baz = foo; // Circular reference!
execRecursively((obj) => console.log(obj), foo);
```
Here, a `WeakSet` is created on the first run, and passed along with every subsequent function call (using the internal `_refs` parameter).
The number of objects or their traversal order is immaterial, so a `WeakSet` is more suitable (and performant) than a {{jsxref("Set")}} for tracking object references, especially if a very large number of objects is involved.
## Constructor
- {{jsxref("WeakSet/WeakSet", "WeakSet()")}}
- : Creates a new `WeakSet` object.
## Instance properties
These properties are defined on `WeakSet.prototype` and shared by all `WeakSet` instances.
- {{jsxref("Object/constructor", "WeakSet.prototype.constructor")}}
- : The constructor function that created the instance object. For `WeakSet` instances, the initial value is the {{jsxref("WeakSet/WeakSet", "WeakSet")}} constructor.
- `WeakSet.prototype[@@toStringTag]`
- : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"WeakSet"`. This property is used in {{jsxref("Object.prototype.toString()")}}.
## Instance methods
- {{jsxref("WeakSet.prototype.add()")}}
- : Appends `value` to the `WeakSet` object.
- {{jsxref("WeakSet.prototype.delete()")}}
- : Removes `value` from the `WeakSet`. `WeakSet.prototype.has(value)` will return `false` afterwards.
- {{jsxref("WeakSet.prototype.has()")}}
- : Returns a boolean asserting whether `value` is present in the `WeakSet` object or not.
## Examples
### Using the WeakSet object
```js
const ws = new WeakSet();
const foo = {};
const bar = {};
ws.add(foo);
ws.add(bar);
ws.has(foo); // true
ws.has(bar); // true
ws.delete(foo); // removes foo from the set
ws.has(foo); // false, foo has been removed
ws.has(bar); // true, bar is retained
```
Note that `foo !== bar`. While they are similar objects, _they are not **the same object**_. And so they are both added to the set.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `WeakSet` in `core-js`](https://github.com/zloirock/core-js#weakset)
- {{jsxref("Map")}}
- {{jsxref("Set")}}
- {{jsxref("WeakMap")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakset | data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakset/weakset/index.md | ---
title: WeakSet() constructor
slug: Web/JavaScript/Reference/Global_Objects/WeakSet/WeakSet
page-type: javascript-constructor
browser-compat: javascript.builtins.WeakSet.WeakSet
---
{{JSRef}}
The **`WeakSet()`** constructor creates {{jsxref("WeakSet")}} objects.
## Syntax
```js-nolint
new WeakSet()
new WeakSet(iterable)
```
> **Note:** `WeakSet()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}.
### Parameters
- `iterable` {{optional_inline}}
- : If an [iterable object](/en-US/docs/Web/JavaScript/Reference/Statements/for...of) is passed, all of its elements will be added to the new `WeakSet`. `null` is treated as `undefined`.
## Examples
### Using the WeakSet object
```js
const ws = new WeakSet();
const foo = {};
const bar = {};
ws.add(foo);
ws.add(bar);
ws.has(foo); // true
ws.has(bar); // true
ws.delete(foo); // removes foo from the set
ws.has(foo); // false, foo has been removed
ws.has(bar); // true, bar is retained
```
Note that `foo !== bar`. While they are similar objects, _they are not
**the same object**_. And so they are both added to the set.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `WeakSet` in `core-js`](https://github.com/zloirock/core-js#weakset)
- {{jsxref("WeakSet")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakset | data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakset/add/index.md | ---
title: WeakSet.prototype.add()
slug: Web/JavaScript/Reference/Global_Objects/WeakSet/add
page-type: javascript-instance-method
browser-compat: javascript.builtins.WeakSet.add
---
{{JSRef}}
The **`add()`** method of {{jsxref("WeakSet")}} instances appends a new object to the end of this `WeakSet`.
{{EmbedInteractiveExample("pages/js/weakset-prototype-add.html", "taller")}}
## Syntax
```js-nolint
add(value)
```
### Parameters
- `value`
- : Must be either an object or a [non-registered symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry). The value to add to the `WeakSet` collection.
### Return value
The `WeakSet` object.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if `value` is not an object or a [non-registered symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry).
## Examples
### Using add
```js
const ws = new WeakSet();
ws.add(window); // add the window object to the WeakSet
ws.has(window); // true
// WeakSet only takes objects as arguments
ws.add(1);
// results in "TypeError: Invalid value used in weak set" in Chrome
// and "TypeError: 1 is not a non-null object" in Firefox
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("WeakSet")}}
- {{jsxref("WeakSet.prototype.delete()")}}
- {{jsxref("WeakSet.prototype.has()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakset | data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakset/has/index.md | ---
title: WeakSet.prototype.has()
slug: Web/JavaScript/Reference/Global_Objects/WeakSet/has
page-type: javascript-instance-method
browser-compat: javascript.builtins.WeakSet.has
---
{{JSRef}}
The **`has()`** method of {{jsxref("WeakSet")}} instances returns a boolean indicating whether an
object exists in this `WeakSet` or not.
{{EmbedInteractiveExample("pages/js/weakset-prototype-has.html")}}
## Syntax
```js-nolint
has(value)
```
### Parameters
- `value`
- : The value to test for presence in the `WeakSet`.
### Return value
Returns `true` if an element with the specified value exists in the `WeakSet` object; otherwise `false`. Always returns `false` if `value` is not an object or a [non-registered symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry).
## Examples
### Using the `has()` method
```js
const ws = new WeakSet();
const obj = {};
ws.add(window);
ws.has(window); // returns true
ws.has(obj); // returns false
// Storing a non-registered symbol
const sym = Symbol("foo");
ws.add(sym);
ws.add(Symbol.iterator);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("WeakSet")}}
- {{jsxref("WeakSet.prototype.add()")}}
- {{jsxref("WeakSet.prototype.delete()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakset | data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakset/delete/index.md | ---
title: WeakSet.prototype.delete()
slug: Web/JavaScript/Reference/Global_Objects/WeakSet/delete
page-type: javascript-instance-method
browser-compat: javascript.builtins.WeakSet.delete
---
{{JSRef}}
The **`delete()`** method of {{jsxref("WeakSet")}} instances removes the specified element from this `WeakSet`.
{{EmbedInteractiveExample("pages/js/weakset-prototype-delete.html")}}
## Syntax
```js-nolint
weakSetInstance.delete(value)
```
### Parameters
- `value`
- : The value to remove from the `WeakSet` object.
### Return value
`true` if an element in the `WeakSet` object has been removed successfully. `false` if the `value` is not found in the `WeakSet`. Always returns `false` if `value` is not an object or a [non-registered symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry).
## Examples
### Using the delete() method
```js
const ws = new WeakSet();
const obj = {};
ws.add(window);
ws.delete(obj); // Returns false. No obj found to be deleted.
ws.delete(window); // Returns true. Successfully removed.
ws.has(window); // Returns false. The window is no longer present in the WeakSet.
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("WeakSet")}}
- {{jsxref("WeakSet.prototype.add()")}}
- {{jsxref("WeakSet.prototype.has()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/decodeuricomponent/index.md | ---
title: decodeURIComponent()
slug: Web/JavaScript/Reference/Global_Objects/decodeURIComponent
page-type: javascript-function
browser-compat: javascript.builtins.decodeURIComponent
---
{{jsSidebar("Objects")}}
The **`decodeURIComponent()`** function decodes a Uniform Resource Identifier (URI) component previously created by {{jsxref("encodeURIComponent()")}} or by a similar routine.
{{EmbedInteractiveExample("pages/js/globalprops-decodeuricomponent.html")}}
## Syntax
```js-nolint
decodeURIComponent(encodedURI)
```
### Parameters
- `encodedURI`
- : An encoded component of a Uniform Resource Identifier.
### Return value
A new string representing the decoded version of the given encoded Uniform Resource Identifier (URI) component.
### Exceptions
- {{jsxref("URIError")}}
- : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character.
## Description
`decodeURIComponent()` is a function property of the global object.
`decodeURIComponent()` uses the same decoding algorithm as described in {{jsxref("decodeURI()")}}. It decodes _all_ escape sequences, including those that are not created by {{jsxref("encodeURIComponent")}}, like `-.!~*'()`.
## Examples
### Decoding a Cyrillic URL component
```js
decodeURIComponent("JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B");
// "JavaScript_ΡΠ΅Π»Π»Ρ"
```
### Catching errors
```js
try {
const a = decodeURIComponent("%E0%A4%A");
} catch (e) {
console.error(e);
}
// URIError: malformed URI sequence
```
### Decoding query parameters from a URL
`decodeURIComponent()` cannot be used directly to parse query parameters from a URL. It needs a bit of preparation.
```js
function decodeQueryParam(p) {
return decodeURIComponent(p.replace(/\+/g, " "));
}
decodeQueryParam("search+query%20%28correct%29");
// 'search query (correct)'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("decodeURI")}}
- {{jsxref("encodeURI")}}
- {{jsxref("encodeURIComponent")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/map/index.md | ---
title: Map
slug: Web/JavaScript/Reference/Global_Objects/Map
page-type: javascript-class
browser-compat: javascript.builtins.Map
---
{{JSRef}}
The **`Map`** object holds key-value pairs and remembers the original insertion order of the keys.
Any value (both objects and {{Glossary("Primitive", "primitive values")}}) may be used as either a key or a value.
{{EmbedInteractiveExample("pages/js/map.html", "taller")}}
## Description
`Map` objects are collections of key-value pairs. A key in the `Map` **may only occur once**; it is unique in the `Map`'s collection. A `Map` object is iterated by key-value pairs β a {{jsxref("Statements/for...of", "for...of")}} loop returns a 2-member array of `[key, value]` for each iteration. Iteration happens in _insertion order_, which corresponds to the order in which each key-value pair was first inserted into the map by the [`set()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/set) method (that is, there wasn't a key with the same value already in the map when `set()` was called).
The specification requires maps to be implemented "that, on average, provide access times that are sublinear on the number of elements in the collection". Therefore, it could be represented internally as a hash table (with O(1) lookup), a search tree (with O(log(N)) lookup), or any other data structure, as long as the complexity is better than O(N).
### Key equality
Value equality is based on the [SameValueZero](/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value-zero_equality) algorithm. (It used to use [SameValue](/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value_equality_using_object.is), which treated `0` and `-0` as different. Check [browser compatibility](#browser_compatibility).) This means {{jsxref("NaN")}} is considered the same as `NaN` (even though `NaN !== NaN`) and all other values are considered equal according to the semantics of the `===` operator.
### Objects vs. Maps
{{jsxref("Object")}} is similar to `Map`βboth let you set keys to
values, retrieve those values, delete keys, and detect whether something is
stored at a key. For this reason (and because there were no built-in
alternatives), `Object` has been used as `Map` historically.
However, there are important differences that make `Map` preferable in some
cases:
<table class="standard-table">
<thead>
<tr>
<th scope="row"></th>
<th scope="col">Map</th>
<th scope="col">Object</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Accidental Keys</th>
<td>
A <code>Map</code> does not contain any keys by default. It only
contains what is explicitly put into it.
</td>
<td>
<p>
An <code>Object</code> has a prototype, so it contains default keys
that could collide with your own keys if you're not careful.
</p>
<div class="notecard note">
<p>
<strong>Note:</strong> This can be bypassed by using
{{jsxref("Object.create", "Object.create(null)")}},
but this is seldom done.
</p>
</div>
</td>
</tr>
<tr>
<th scope="row">Security</th>
<td>
A <code>Map</code> is safe to use with user-provided keys and values.
</td>
<td>
<p>
Setting user-provided key-value pairs on an <code>Object</code> may allow
an attacker to override the object's prototype, which can lead to
<a href="https://github.com/eslint-community/eslint-plugin-security/blob/main/docs/the-dangers-of-square-bracket-notation.md">
object injection attacks
</a>. Like the accidental keys issue, this can also be mitigated by using
a <code>null</code>-prototype object.
</p>
</td>
</tr>
<tr>
<th scope="row">Key Types</th>
<td>
A <code>Map</code>'s keys can be any value (including functions,
objects, or any primitive).
</td>
<td>
The keys of an <code>Object</code> must be either a
{{jsxref("String")}} or a {{jsxref("Symbol")}}.
</td>
</tr>
<tr>
<th scope="row">Key Order</th>
<td>
<p>
The keys in <code>Map</code> are ordered in a simple, straightforward
way: A <code>Map</code> object iterates entries, keys, and values in
the order of entry insertion.
</p>
</td>
<td>
<p>
Although the keys of an ordinary <code>Object</code> are ordered now,
this was not always the case, and the order is complex. As a result,
it's best not to rely on property order.
</p>
<p>
The order was first defined for own properties only in ECMAScript
2015; ECMAScript 2020 defines order for inherited properties as well.
But note that no single mechanism
iterates
<strong>all</strong> of an object's properties; the various mechanisms
each include different subsets of properties.
({{jsxref("Statements/for...in",
"for-in")}}
includes only enumerable string-keyed properties;
{{jsxref("Object.keys")}} includes only own, enumerable,
string-keyed properties;
{{jsxref("Object.getOwnPropertyNames")}} includes own,
string-keyed properties even if non-enumerable;
{{jsxref("Object.getOwnPropertySymbols")}} does the same
for just <code>Symbol</code>-keyed properties, etc.)
</p>
</td>
</tr>
<tr>
<th scope="row"><p>Size</p></th>
<td>
The number of items in a <code>Map</code> is easily retrieved from its
{{jsxref("Map.prototype.size", "size")}} property.
</td>
<td>
Determining the number of items in an <code>Object</code> is more roundabout and less efficient. A common way to do it is through the {{jsxref("Array/length", "length")}} of the array returned from {{jsxref("Object.keys()")}}.
</td>
</tr>
<tr>
<th scope="row">Iteration</th>
<td>
A <code>Map</code> is an
<a href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols"
>iterable</a
>, so it can be directly iterated.
</td>
<td>
<p>
<code>Object</code> does not implement an <a
href="/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol"
>iteration protocol</a
>, and so objects are not directly iterable using the JavaScript
<a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of"
>for...of</a
>
statement (by default).
</p>
<div class="notecard note">
<p><strong>Note:</strong></p>
<ul>
<li>
An object can implement the iteration protocol, or you can get an
iterable for an object using <a
href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys"
><code>Object.keys</code></a
> or <a
href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries"
><code>Object.entries</code></a
>.
</li>
<li>
The
<a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in"
>for...in</a
>
statement allows you to iterate over the
<em>enumerable</em> properties of an object.
</li>
</ul>
</div>
</td>
</tr>
<tr>
<th scope="row">Performance</th>
<td>
<p>
Performs better in scenarios involving frequent additions and removals
of key-value pairs.
</p>
</td>
<td>
<p>
Not optimized for frequent additions and removals of key-value pairs.
</p>
</td>
</tr>
<tr>
<th scope="row">Serialization and parsing</th>
<td>
<p>No native support for serialization or parsing.</p>
<p>
(But you can build your own serialization and parsing support for
<code>Map</code> by using {{jsxref("JSON.stringify()")}}
with its <em>replacer</em> argument, and by using
{{jsxref("JSON.parse()")}} with its
<em>reviver</em> argument. See the Stack Overflow question
<a href="https://stackoverflow.com/q/29085197/"
>How do you JSON.stringify an ES6 Map?</a
>).
</p>
</td>
<td>
<p>
Native support for serialization from {{jsxref("Object")}} to
JSON, using {{jsxref("JSON.stringify()")}}.
</p>
<p>
Native support for parsing from JSON to {{jsxref("Object")}},
using {{jsxref("JSON.parse()")}}.
</p>
</td>
</tr>
</tbody>
</table>
### Setting object properties
Setting Object properties works for Map objects as well, and can cause
considerable confusion.
Therefore, this appears to work in a way:
```js example-bad
const wrongMap = new Map();
wrongMap["bla"] = "blaa";
wrongMap["bla2"] = "blaaa2";
console.log(wrongMap); // Map { bla: 'blaa', bla2: 'blaaa2' }
```
But that way of setting a property does not interact with the Map data
structure. It uses the feature of the generic object. The value of 'bla' is not
stored in the Map for queries. Other operations on the data fail:
```js example-bad
wrongMap.has("bla"); // false
wrongMap.delete("bla"); // false
console.log(wrongMap); // Map { bla: 'blaa', bla2: 'blaaa2' }
```
The correct usage for storing data in the Map is through the `set(key, value)`
method.
```js example-good
const contacts = new Map();
contacts.set("Jessie", { phone: "213-555-1234", address: "123 N 1st Ave" });
contacts.has("Jessie"); // true
contacts.get("Hilary"); // undefined
contacts.set("Hilary", { phone: "617-555-4321", address: "321 S 2nd St" });
contacts.get("Jessie"); // {phone: "213-555-1234", address: "123 N 1st Ave"}
contacts.delete("Raymond"); // false
contacts.delete("Jessie"); // true
console.log(contacts.size); // 1
```
### Map-like browser APIs
**Browser `Map`-like objects** (or "maplike objects") are [Web API](/en-US/docs/Web/API) interfaces that behave in many ways like a `Map`.
Just like `Map`, entries can be iterated in the same order that they were added to the object.
`Map`-like objects and `Map` also have properties and methods that share the same name and behavior.
However unlike `Map` they only allow specific predefined types for the keys and values of each entry.
The allowed types are set in the specification IDL definition.
For example, {{domxref("RTCStatsReport")}} is a `Map`-like object that must use strings for keys and objects for values.
This is defined in the specification IDL below:
```webidl
interface RTCStatsReport {
readonly maplike<DOMString, object>;
};
```
`Map`-like objects are either read-only or read-writable (see the `readonly` keyword in the IDL above).
- Read-only `Map`-like objects have the property [`size`](#map.prototype.size), and the methods: [`entries()`](#map.prototype.entries), [`forEach()`](#map.prototype.foreach), [`get()`](#map.prototype.get), [`has()`](#map.prototype.has), [`keys()`](#map.prototype.keys), [`values()`](#map.prototype.values), and [`@@iterator`](#map.prototypeiterator).
- Writeable `Map`-like objects additionally have the methods: [`clear()`](#map.prototype.clear), [`delete()`](#map.prototype.delete), and [`set()`](#map.prototype.set).
The methods and properties have the same behavior as the equivalent entities in `Map`, except for the restriction on the types of the keys and values.
The following are examples of read-only `Map`-like browser objects:
- {{domxref("AudioParamMap")}}
- {{domxref("RTCStatsReport")}}
- {{domxref("EventCounts")}}
- {{domxref("KeyboardLayoutMap")}}
- {{domxref("MIDIInputMap")}}
- {{domxref("MIDIOutputMap")}}
## Constructor
- {{jsxref("Map/Map", "Map()")}}
- : Creates a new `Map` object.
## Static properties
- {{jsxref("Map/@@species", "Map[@@species]")}}
- : The constructor function that is used to create derived objects.
## Static methods
- {{jsxref("Map.groupBy()")}}
- : Groups the elements of a given iterable using the values returned by a provided callback function. The final returned `Map` uses the unique values from the test function as keys, which can be used to get the array of elements in each group.
## Instance properties
These properties are defined on `Map.prototype` and shared by all `Map` instances.
- {{jsxref("Object/constructor", "Map.prototype.constructor")}}
- : The constructor function that created the instance object. For `Map` instances, the initial value is the {{jsxref("Map/Map", "Map")}} constructor.
- {{jsxref("Map.prototype.size")}}
- : Returns the number of key/value pairs in the `Map` object.
- `Map.prototype[@@toStringTag]`
- : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"Map"`. This property is used in {{jsxref("Object.prototype.toString()")}}.
## Instance methods
- {{jsxref("Map.prototype.clear()")}}
- : Removes all key-value pairs from the `Map` object.
- {{jsxref("Map.prototype.delete()")}}
- : Returns `true` if an element in the `Map` object existed and has been
removed, or `false` if the element does not exist. `map.has(key)`
will return `false` afterwards.
- {{jsxref("Map.prototype.entries()")}}
- : Returns a new Iterator object that contains a two-member array of `[key, value]` for each element in the `Map` object in insertion order.
- {{jsxref("Map.prototype.forEach()")}}
- : Calls `callbackFn` once for each key-value pair present in the `Map` object, in insertion order. If a `thisArg` parameter is provided to `forEach`, it will be used as the `this` value for each callback.
- {{jsxref("Map.prototype.get()")}}
- : Returns the value associated to the passed key, or `undefined` if there is none.
- {{jsxref("Map.prototype.has()")}}
- : Returns a boolean indicating whether a value has been associated with the passed key in the `Map` object or not.
- {{jsxref("Map.prototype.keys()")}}
- : Returns a new Iterator object that contains the keys for each element in the `Map` object in insertion order.
- {{jsxref("Map.prototype.set()")}}
- : Sets the value for the passed key in the `Map` object. Returns the `Map` object.
- {{jsxref("Map.prototype.values()")}}
- : Returns a new Iterator object that contains the values for each element in the `Map` object in insertion order.
- [`Map.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/@@iterator)
- : Returns a new Iterator object that contains a two-member array of `[key, value]` for each element in the `Map` object in insertion order.
## Examples
### Using the Map object
```js
const myMap = new Map();
const keyString = "a string";
const keyObj = {};
const keyFunc = function () {};
// setting the values
myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");
console.log(myMap.size); // 3
// getting the values
console.log(myMap.get(keyString)); // "value associated with 'a string'"
console.log(myMap.get(keyObj)); // "value associated with keyObj"
console.log(myMap.get(keyFunc)); // "value associated with keyFunc"
console.log(myMap.get("a string")); // "value associated with 'a string'", because keyString === 'a string'
console.log(myMap.get({})); // undefined, because keyObj !== {}
console.log(myMap.get(function () {})); // undefined, because keyFunc !== function () {}
```
### Using NaN as Map keys
{{jsxref("NaN")}} can also be used as a key. Even though every `NaN` is
not equal to itself (`NaN !== NaN` is true), the following example works because
`NaN`s are indistinguishable from each other:
```js
const myMap = new Map();
myMap.set(NaN, "not a number");
myMap.get(NaN);
// "not a number"
const otherNaN = Number("foo");
myMap.get(otherNaN);
// "not a number"
```
### Iterating Map with for...of
Maps can be iterated using a `for...of` loop:
```js
const myMap = new Map();
myMap.set(0, "zero");
myMap.set(1, "one");
for (const [key, value] of myMap) {
console.log(`${key} = ${value}`);
}
// 0 = zero
// 1 = one
for (const key of myMap.keys()) {
console.log(key);
}
// 0
// 1
for (const value of myMap.values()) {
console.log(value);
}
// zero
// one
for (const [key, value] of myMap.entries()) {
console.log(`${key} = ${value}`);
}
// 0 = zero
// 1 = one
```
### Iterating Map with forEach()
Maps can be iterated using the
{{jsxref("Map/forEach", "forEach()")}} method:
```js
myMap.forEach((value, key) => {
console.log(`${key} = ${value}`);
});
// 0 = zero
// 1 = one
```
### Relation with Array objects
```js
const kvArray = [
["key1", "value1"],
["key2", "value2"],
];
// Use the regular Map constructor to transform a 2D key-value Array into a map
const myMap = new Map(kvArray);
console.log(myMap.get("key1")); // "value1"
// Use Array.from() to transform a map into a 2D key-value Array
console.log(Array.from(myMap)); // Will show you exactly the same Array as kvArray
// A succinct way to do the same, using the spread syntax
console.log([...myMap]);
// Or use the keys() or values() iterators, and convert them to an array
console.log(Array.from(myMap.keys())); // ["key1", "key2"]
```
### Cloning and merging Maps
Just like `Array`s, `Map`s can be cloned:
```js
const original = new Map([[1, "one"]]);
const clone = new Map(original);
console.log(clone.get(1)); // one
console.log(original === clone); // false (useful for shallow comparison)
```
> **Note:** Keep in mind that _the data itself_ is not cloned.
Maps can be merged, maintaining key uniqueness:
```js
const first = new Map([
[1, "one"],
[2, "two"],
[3, "three"],
]);
const second = new Map([
[1, "uno"],
[2, "dos"],
]);
// Merge two maps. The last repeated key wins.
// Spread syntax essentially converts a Map to an Array
const merged = new Map([...first, ...second]);
console.log(merged.get(1)); // uno
console.log(merged.get(2)); // dos
console.log(merged.get(3)); // three
```
Maps can be merged with Arrays, too:
```js
const first = new Map([
[1, "one"],
[2, "two"],
[3, "three"],
]);
const second = new Map([
[1, "uno"],
[2, "dos"],
]);
// Merge maps with an array. The last repeated key wins.
const merged = new Map([...first, ...second, [1, "eins"]]);
console.log(merged.get(1)); // eins
console.log(merged.get(2)); // dos
console.log(merged.get(3)); // three
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill for `Map` in `core-js`](https://github.com/zloirock/core-js#map)
- {{jsxref("Set")}}
- {{jsxref("WeakMap")}}
- {{jsxref("WeakSet")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/map | data/mdn-content/files/en-us/web/javascript/reference/global_objects/map/map/index.md | ---
title: Map() constructor
slug: Web/JavaScript/Reference/Global_Objects/Map/Map
page-type: javascript-constructor
browser-compat: javascript.builtins.Map.Map
---
{{JSRef}}
The **`Map()`** constructor creates {{jsxref("Map")}} objects.
## Syntax
```js-nolint
new Map()
new Map(iterable)
```
> **Note:** `Map()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}.
### Parameters
- `iterable` {{optional_inline}}
- : An {{jsxref("Array")}} or other
[iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) object
whose elements are key-value pairs. (For example, arrays with two elements,
such as `[[ 1, 'one' ],[ 2, 'two' ]]`.) Each key-value pair is added to the
new `Map`.
## Examples
### Creating a new Map
```js
const myMap = new Map([
[1, "one"],
[2, "two"],
[3, "three"],
]);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill for `Map` in `core-js`](https://github.com/zloirock/core-js#map)
- {{jsxref("Set")}}
- {{jsxref("WeakMap")}}
- {{jsxref("WeakSet")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/map | data/mdn-content/files/en-us/web/javascript/reference/global_objects/map/groupby/index.md | ---
title: Map.groupBy()
slug: Web/JavaScript/Reference/Global_Objects/Map/groupBy
page-type: javascript-static-method
browser-compat: javascript.builtins.Map.groupBy
---
{{JSRef}}
> **Note:** In some versions of some browsers, this method was implemented as the method `Array.prototype.groupToMap()`. Due to web compatibility issues, it is now implemented as a static method. Check the [browser compatibility table](#browser_compatibility) for details.
The **`Map.groupBy()`** static method groups the elements of a given iterable using the values returned by a provided callback function. The final returned {{jsxref("Map")}} uses the unique values from the test function as keys, which can be used to get the array of elements in each group.
The method is primarily useful when grouping elements that are associated with an object, and in particular when that object might change over time. If the object is invariant, you might instead represent it using a string, and group elements with {{jsxref("Object.groupBy()")}}.
{{EmbedInteractiveExample("pages/js/map-groupby.html", "taller")}}
## Syntax
```js-nolint
Map.groupBy(items, callbackFn)
```
### Parameters
- `items`
- : An [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an {{jsxref("Array")}}) whose elements will be grouped.
- `callbackFn`
- : A function to execute for each element in the iterable. It should return a value ({{Glossary("object")}} or {{Glossary("primitive")}}) indicating the group of the current element. The function is called with the following arguments:
- `element`
- : The current element being processed.
- `index`
- : The index of the current element being processed.
### Return value
A {{jsxref("Map")}} object with keys for each group, each assigned to an array containing the elements of the associated group.
## Description
`Map.groupBy()` calls a provided `callbackFn` function once for each element in an iterable. The callback function should return a value indicating the group of the associated element. The values returned by `callbackFn` are used as keys for the {{jsxref("Map")}} returned by `Map.groupBy()`. Each key has an associated array containing all the elements for which the callback returned the same value.
The elements in the returned {{jsxref("Map")}} and the original iterable are the same (not {{Glossary("deep copy", "deep copies")}}). Changing the internal structure of the elements will be reflected in both the original iterable and the returned {{jsxref("Map")}}.
This method is useful when you need to group information that is related to a particular object that might potentially change over time. This is because even if the object is modified, it will continue to work as a key to the returned `Map`. If you instead create a string representation for the object and use that as a grouping key in {{jsxref("Object.groupBy()")}}, you must maintain the mapping between the original object and its representation as the object changes.
> **Note:** To access the groups in the returned `Map`, you must use the same object that was originally used as a key in the `Map` (although you may modify its properties). You can't use another object that just happens to have the same name and properties.
`Map.groupBy` does not read the value of `this`. It can be called on any object and a new {{jsxref("Map")}} instance will be returned.
## Examples
### Using Map.groupBy()
First we define an array containing objects representing an inventory of different foodstuffs. Each food has a `type` and a `quantity`.
```js
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 9 },
{ name: "bananas", type: "fruit", quantity: 5 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 12 },
{ name: "fish", type: "meat", quantity: 22 },
];
```
The code below uses `Map.groupBy()` with an arrow function that returns the object keys named `restock` or `sufficient`, depending on whether the element has `quantity < 6`. The returned `result` object is a `Map` so we need to call `get()` with the key to obtain the array.
```js
const restock = { restock: true };
const sufficient = { restock: false };
const result = Map.groupBy(inventory, ({ quantity }) =>
quantity < 6 ? restock : sufficient,
);
console.log(result.get(restock));
// [{ name: "bananas", type: "fruit", quantity: 5 }]
```
Note that the function argument `{ quantity }` is a basic example of [object destructuring syntax for function arguments](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#unpacking_properties_from_objects_passed_as_a_function_parameter). This unpacks the `quantity` property of an object passed as a parameter, and assigns it to a variable named `quantity` in the body of the function. This is a very succinct way to access the relevant values of elements within a function.
The key to a `Map` can be modified and still used. However you can't recreate the key and still use it. For this reason it is important that anything that needs to use the map keeps a reference to its keys.
```js
// The key can be modified and still used
restock["fast"] = true;
console.log(result.get(restock));
// [{ name: "bananas", type: "fruit", quantity: 5 }]
// A new key can't be used, even if it has the same structure!
const restock2 = { restock: true };
console.log(result.get(restock2)); // undefined
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Map.groupBy` in `core-js`](https://github.com/zloirock/core-js#array-grouping)
- [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide
- {{jsxref("Array.prototype.reduce()")}}
- {{jsxref("Map/Map", "Map()")}}
- {{jsxref("Object.groupBy()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/map | data/mdn-content/files/en-us/web/javascript/reference/global_objects/map/get/index.md | ---
title: Map.prototype.get()
slug: Web/JavaScript/Reference/Global_Objects/Map/get
page-type: javascript-instance-method
browser-compat: javascript.builtins.Map.get
---
{{JSRef}}
The **`get()`** method of {{jsxref("Map")}} instances returns a specified element from this map. If the
value that is associated to the provided key is an object, then you will get a
reference to that object and any change made to that object will effectively
modify it inside the `Map` object.
{{EmbedInteractiveExample("pages/js/map-prototype-get.html")}}
## Syntax
```js-nolint
get(key)
```
### Parameters
- `key`
- : The key of the element to return from the `Map` object.
### Return value
The element associated with the specified key, or
{{jsxref("undefined")}} if the key can't be found in the `Map` object.
## Examples
### Using get()
```js
const myMap = new Map();
myMap.set("bar", "foo");
console.log(myMap.get("bar")); // Returns "foo"
console.log(myMap.get("baz")); // Returns undefined
```
### Using get() to retrieve a reference to an object
```js
const arr = [];
const myMap = new Map();
myMap.set("bar", arr);
myMap.get("bar").push("foo");
console.log(arr); // ["foo"]
console.log(myMap.get("bar")); // ["foo"]
```
Note that the map holding a reference to the original object effectively means the object cannot be garbage-collected, which may lead to unexpected memory issues. If you want the object stored in the map to have the same lifespan as the original one, consider using a {{jsxref("WeakMap")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Map")}}
- {{jsxref("Map.prototype.set()")}}
- {{jsxref("Map.prototype.has()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/map | data/mdn-content/files/en-us/web/javascript/reference/global_objects/map/has/index.md | ---
title: Map.prototype.has()
slug: Web/JavaScript/Reference/Global_Objects/Map/has
page-type: javascript-instance-method
browser-compat: javascript.builtins.Map.has
---
{{JSRef}}
The **`has()`** method of {{jsxref("Map")}} instances returns a boolean indicating whether an element with the
specified key exists in this map or not.
{{EmbedInteractiveExample("pages/js/map-prototype-has.html")}}
## Syntax
```js-nolint
has(key)
```
### Parameters
- `key`
- : The key of the element to test for presence in the `Map` object.
### Return value
`true` if an element with the specified key exists in the `Map` object;
otherwise `false`.
## Examples
### Using has()
```js
const myMap = new Map();
myMap.set("bar", "foo");
console.log(myMap.has("bar")); // true
console.log(myMap.has("baz")); // false
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Map")}}
- {{jsxref("Map.prototype.set()")}}
- {{jsxref("Map.prototype.get()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/map | data/mdn-content/files/en-us/web/javascript/reference/global_objects/map/set/index.md | ---
title: Map.prototype.set()
slug: Web/JavaScript/Reference/Global_Objects/Map/set
page-type: javascript-instance-method
browser-compat: javascript.builtins.Map.set
---
{{JSRef}}
The **`set()`** method of {{jsxref("Map")}} instances adds or updates an entry in this map with a specified key and a value.
{{EmbedInteractiveExample("pages/js/map-prototype-set.html")}}
## Syntax
```js-nolint
set(key, value)
```
### Parameters
- `key`
- : The key of the element to add to the `Map` object. The key may be any [JavaScript type](/en-US/docs/Web/JavaScript/Data_structures) (any [primitive value](/en-US/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](/en-US/docs/Web/JavaScript/Data_structures#objects)).
- `value`
- : The value of the element to add to the `Map` object. The value may be any [JavaScript type](/en-US/docs/Web/JavaScript/Data_structures) (any [primitive value](/en-US/docs/Web/JavaScript/Data_structures#primitive_values) or any type of [JavaScript object](/en-US/docs/Web/JavaScript/Data_structures#objects)).
### Return value
The `Map` object.
## Examples
### Using set()
```js
const myMap = new Map();
// Add new elements to the map
myMap.set("bar", "foo");
myMap.set(1, "foobar");
// Update an element in the map
myMap.set("bar", "baz");
```
### Using the set() with chaining
Since the `set()` method returns back the same `Map` object, you can chain the
method call like below:
```js
// Add new elements to the map with chaining.
myMap.set("bar", "foo").set(1, "foobar").set(2, "baz");
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Map")}}
- {{jsxref("Map.prototype.get()")}}
- {{jsxref("Map.prototype.has()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/map | data/mdn-content/files/en-us/web/javascript/reference/global_objects/map/keys/index.md | ---
title: Map.prototype.keys()
slug: Web/JavaScript/Reference/Global_Objects/Map/keys
page-type: javascript-instance-method
browser-compat: javascript.builtins.Map.keys
---
{{JSRef}}
The **`keys()`** method of {{jsxref("Map")}} instances returns a new _[map iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator)_ object that contains the keys for each element in this map in insertion order.
{{EmbedInteractiveExample("pages/js/map-prototype-keys.html")}}
## Syntax
```js-nolint
keys()
```
### Parameters
None.
### Return value
A new [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator).
## Examples
### Using keys()
```js
const myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
const mapIter = myMap.keys();
console.log(mapIter.next().value); // "0"
console.log(mapIter.next().value); // 1
console.log(mapIter.next().value); // {}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Map.prototype.entries()")}}
- {{jsxref("Map.prototype.values()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/map | data/mdn-content/files/en-us/web/javascript/reference/global_objects/map/clear/index.md | ---
title: Map.prototype.clear()
slug: Web/JavaScript/Reference/Global_Objects/Map/clear
page-type: javascript-instance-method
browser-compat: javascript.builtins.Map.clear
---
{{JSRef}}
The **`clear()`** method of {{jsxref("Map")}} instances removes all elements from this map.
{{EmbedInteractiveExample("pages/js/map-prototype-clear.html")}}
## Syntax
```js-nolint
clear()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
## Examples
### Using clear()
```js
const myMap = new Map();
myMap.set("bar", "baz");
myMap.set(1, "foo");
console.log(myMap.size); // 2
console.log(myMap.has("bar")); // true
myMap.clear();
console.log(myMap.size); // 0
console.log(myMap.has("bar")); // false
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Map")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/map | data/mdn-content/files/en-us/web/javascript/reference/global_objects/map/size/index.md | ---
title: Map.prototype.size
slug: Web/JavaScript/Reference/Global_Objects/Map/size
page-type: javascript-instance-accessor-property
browser-compat: javascript.builtins.Map.size
---
{{JSRef}}
The **`size`** accessor property of {{jsxref("Map")}} instances returns the number of elements in this map.
{{EmbedInteractiveExample("pages/js/map-prototype-size.html")}}
## Description
The value of `size` is an integer representing how many entries the `Map` object
has. A set accessor function for `size` is `undefined`; you can not change this
property.
## Examples
### Using size
```js
const myMap = new Map();
myMap.set("a", "alpha");
myMap.set("b", "beta");
myMap.set("g", "gamma");
console.log(myMap.size); // 3
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Map")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/map | data/mdn-content/files/en-us/web/javascript/reference/global_objects/map/values/index.md | ---
title: Map.prototype.values()
slug: Web/JavaScript/Reference/Global_Objects/Map/values
page-type: javascript-instance-method
browser-compat: javascript.builtins.Map.values
---
{{JSRef}}
The **`values()`** method of {{jsxref("Map")}} instances returns a new _[map iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator)_ object that contains the values for each element in this map in insertion order.
{{EmbedInteractiveExample("pages/js/map-prototype-values.html")}}
## Syntax
```js-nolint
values()
```
### Parameters
None.
### Return value
A new [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator).
## Examples
### Using values()
```js
const myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
const mapIter = myMap.values();
console.log(mapIter.next().value); // "foo"
console.log(mapIter.next().value); // "bar"
console.log(mapIter.next().value); // "baz"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Map.prototype.entries()")}}
- {{jsxref("Map.prototype.keys()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/map | data/mdn-content/files/en-us/web/javascript/reference/global_objects/map/@@iterator/index.md | ---
title: Map.prototype[@@iterator]()
slug: Web/JavaScript/Reference/Global_Objects/Map/@@iterator
page-type: javascript-instance-method
browser-compat: javascript.builtins.Map.@@iterator
---
{{JSRef}}
The **`[@@iterator]()`** method of {{jsxref("Map")}} instances implements the [iterable protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) and allows `Map` objects to be consumed by most syntaxes expecting iterables, such as the [spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and {{jsxref("Statements/for...of", "for...of")}} loops. It returns a [map iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) that yields the key-value pairs of the map in insertion order.
The initial value of this property is the same function object as the initial value of the {{jsxref("Map.prototype.entries")}} property.
{{EmbedInteractiveExample("pages/js/map-prototype-@@iterator.html")}}
## Syntax
```js-nolint
map[Symbol.iterator]()
```
### Parameters
None.
### Return value
The same return value as {{jsxref("Map.prototype.entries()")}}: a new [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) that yields the key-value pairs of the map.
## Examples
### Iteration using for...of loop
Note that you seldom need to call this method directly. The existence of the `@@iterator` method makes `Map` objects [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol), and iterating syntaxes like the `for...of` loop automatically call this method to obtain the iterator to loop over.
```js
const myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
for (const entry of myMap) {
console.log(entry);
}
// ["0", "foo"]
// [1, "bar"]
// [{}, "baz"]
for (const [key, value] of myMap) {
console.log(`${key}: ${value}`);
}
// 0: foo
// 1: bar
// [Object]: baz
```
### Manually hand-rolling the iterator
You may still manually call the `next()` method of the returned iterator object to achieve maximum control over the iteration process.
```js
const myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
const mapIter = myMap[Symbol.iterator]();
console.log(mapIter.next().value); // ["0", "foo"]
console.log(mapIter.next().value); // [1, "bar"]
console.log(mapIter.next().value); // [Object, "baz"]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Map")}}
- {{jsxref("Map.prototype.entries()")}}
- {{jsxref("Map.prototype.keys()")}}
- {{jsxref("Map.prototype.values()")}}
- {{jsxref("Symbol.iterator")}}
- [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/map | data/mdn-content/files/en-us/web/javascript/reference/global_objects/map/delete/index.md | ---
title: Map.prototype.delete()
slug: Web/JavaScript/Reference/Global_Objects/Map/delete
page-type: javascript-instance-method
browser-compat: javascript.builtins.Map.delete
---
{{JSRef}}
The **`delete()`** method of {{jsxref("Map")}} instances removes the specified element from this map by
key.
{{EmbedInteractiveExample("pages/js/map-prototype-delete.html")}}
## Syntax
```js-nolint
mapInstance.delete(key)
```
### Parameters
- `key`
- : The key of the element to remove from the `Map` object.
### Return value
`true` if an element in the `Map` object existed and has been removed, or
`false` if the element does not exist.
## Examples
### Using delete()
```js
const myMap = new Map();
myMap.set("bar", "foo");
console.log(myMap.delete("bar")); // Returns true. Successfully removed.
console.log(myMap.has("bar")); // Returns false. The "bar" element is no longer present.
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Map")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/map | data/mdn-content/files/en-us/web/javascript/reference/global_objects/map/foreach/index.md | ---
title: Map.prototype.forEach()
slug: Web/JavaScript/Reference/Global_Objects/Map/forEach
page-type: javascript-instance-method
browser-compat: javascript.builtins.Map.forEach
---
{{JSRef}}
The **`forEach()`** method of {{jsxref("Map")}} instances executes a provided function once per each key/value
pair in this map, in insertion order.
{{EmbedInteractiveExample("pages/js/map-prototype-foreach.html")}}
## Syntax
```js-nolint
forEach(callbackFn)
forEach(callbackFn, thisArg)
```
### Parameters
- `callbackFn`
- : A function to execute for each entry in the map. The function is called with the following arguments:
- `value`
- : Value of each iteration.
- `key`
- : Key of each iteration.
- `map`
- : The map being iterated.
- `thisArg` {{optional_inline}}
- : A value to use as `this` when executing `callbackFn`.
### Return value
None ({{jsxref("undefined")}}).
## Description
The `forEach` method executes the provided `callback` once for each key of the
map which actually exist. It is not invoked for keys which have been deleted.
However, it is executed for values which are present but have the value
`undefined`.
`callback` is invoked with **three arguments**:
- the entry's `value`
- the entry's `key`
- the **`Map` object** being traversed
If a `thisArg` parameter is provided to `forEach`, it will be passed to
`callback` when invoked, for use as its `this` value. Otherwise, the value
`undefined` will be passed for use as its `this` value. The `this` value
ultimately observable by `callback` is determined according to
[the usual rules for determining the `this` seen by a function](/en-US/docs/Web/JavaScript/Reference/Operators/this).
Each value is visited once, except in the case when it was deleted and re-added
before `forEach` has finished. `callback` is not invoked for values deleted
before being visited. New values added before `forEach` has finished will be
visited.
## Examples
### Printing the contents of a Map object
The following code logs a line for each element in an `Map` object:
```js
function logMapElements(value, key, map) {
console.log(`map.get('${key}') = ${value}`);
}
new Map([
["foo", 3],
["bar", {}],
["baz", undefined],
]).forEach(logMapElements);
// Logs:
// "map.get('foo') = 3"
// "map.get('bar') = [object Object]"
// "map.get('baz') = undefined"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Array.prototype.forEach()")}}
- {{jsxref("Set.prototype.forEach()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/map | data/mdn-content/files/en-us/web/javascript/reference/global_objects/map/@@species/index.md | ---
title: Map[@@species]
slug: Web/JavaScript/Reference/Global_Objects/Map/@@species
page-type: javascript-static-accessor-property
browser-compat: javascript.builtins.Map.@@species
---
{{JSRef}}
The **`Map[@@species]`** static accessor property is an unused accessor property specifying how to copy `Map` objects.
## Syntax
```js-nolint
Map[Symbol.species]
```
### Return value
The value of the constructor (`this`) on which `get @@species` was called. The return value is used to construct copied `Map` instances.
## Description
The `@@species` accessor property returns the default constructor for `Map` objects. Subclass constructors may override it to change the constructor assignment.
> **Note:** This property is currently unused by all `Map` methods.
## Examples
### Species in ordinary objects
The `@@species` property returns the default constructor function, which is the `Map` constructor for `Map`.
```js
Map[Symbol.species]; // function Map()
```
### Species in derived objects
In an instance of a custom `Map` subclass, such as `MyMap`, the `MyMap` species is the `MyMap` constructor. However, you might want to overwrite this, in order to return parent `Map` objects in your derived class methods:
```js
class MyMap extends Map {
// Overwrite MyMap species to the parent Map constructor
static get [Symbol.species]() {
return Map;
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Map")}}
- {{jsxref("Symbol.species")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/map | data/mdn-content/files/en-us/web/javascript/reference/global_objects/map/entries/index.md | ---
title: Map.prototype.entries()
slug: Web/JavaScript/Reference/Global_Objects/Map/entries
page-type: javascript-instance-method
browser-compat: javascript.builtins.Map.entries
---
{{JSRef}}
The **`entries()`** method of {{jsxref("Map")}} instances returns a new _[map iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator)_ object that contains the `[key, value]` pairs for each element in this map in insertion order.
{{EmbedInteractiveExample("pages/js/map-prototype-entries.html")}}
## Syntax
```js-nolint
entries()
```
### Parameters
None.
### Return value
A new [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator).
## Examples
### Using entries()
```js
const myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
const mapIter = myMap.entries();
console.log(mapIter.next().value); // ["0", "foo"]
console.log(mapIter.next().value); // [1, "bar"]
console.log(mapIter.next().value); // [Object, "baz"]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Map.prototype.keys()")}}
- {{jsxref("Map.prototype.values()")}}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.