SyntaxError: missing name after . operator - JavaScript

SyntaxError: missing name after . operator
==========================================

 The JavaScript exception "missing name after . operator" occurs when there is a problem
 with how the dot operator (`.`) is used
 for property access.

Message
-------
```

SyntaxError: missing name after . operator (Firefox)
SyntaxError: Unexpected token '['. Expected a property name after '.'. (Safari)
```

Error type
----------

`SyntaxError`What went wrong?
----------------

 The dot operator (`.`) is used for property access.
 You will have to specify the name of the property that you want to access.
 For computed property access, you might need to change your property access from using a
 dot to using square brackets. These will allow you to compute an expression. Maybe you
 intended to do concatenation instead? A plus operator (`+`) is needed in that
 case. Please see the examples below.

Examples
--------

### Property access

Property accessors
 in JavaScript use either the dot (.) or square brackets (`[]`), but not both.
 Square brackets allow computed property access.

```js
const obj = { foo: { bar: "baz", bar2: "baz2" } };
const i = 2;

obj.[foo].[bar]
// SyntaxError: missing name after . operator

obj.foo."bar"+i;
// SyntaxError: missing name after . operator
```

To fix this code, you need to access the object like this:

```js
obj.foo.bar; // "baz"
// or alternatively
obj["foo"]["bar"]; // "baz"

// computed properties require square brackets
obj.foo["bar" + i]; // "baz2"
// or as template literal
obj.foo[`bar${i}`]; // "baz2"
```

### Property access vs. concatenation

 If you are coming from another programming language (like PHP), it is also easy to mix up the dot operator
 (`.`) and the concatenation operator (`+`).

```js
console.log("Hello" . "world");

// SyntaxError: missing name after . operator
```

Instead you need to use a plus sign for concatenation:

```js
console.log("Hello" + "World");
```

See also
--------

* Property accessors


RangeError: invalid date - JavaScript

RangeError: invalid date
========================

 The JavaScript exception "invalid date" occurs when a string leading to an invalid date
 has been provided to `Date` or `Date.parse()`.

Message
-------
```

RangeError: Invalid time value (V8-based)
RangeError: invalid date (Firefox)
RangeError: Invalid Date (Safari)
```

Error type
----------

`RangeError`What went wrong?
----------------

 A string leading to an invalid date has been provided to `Date` or
 `Date.parse()`.

Examples
--------

### Invalid cases

 Unrecognizable strings or dates containing illegal element values in ISO formatted
 strings usually return `NaN`. However, depending on the implementation,
 non–conforming ISO format strings, may also throw `RangeError: invalid date`,
 like the following cases in Firefox:

```js
new Date("foo-bar 2014");
new Date("2014-25-23").toISOString();
new Date("foo-bar 2014").toString();
```

This, however, returns `NaN` in Firefox:

```js
Date.parse("foo-bar 2014"); // NaN
```

For more details, see the `Date.parse()` documentation.

### Valid cases

```js
new Date("05 October 2011 14:48 UTC");
new Date(1317826080); // Unix Timestamp for 05 October 2011 14:48:00 UTC
```

See also
--------

* `Date`
* `Date.prototype.parse()`
* `Date.prototype.toISOString()`


RangeError: precision is out of range - JavaScript

RangeError: precision is out of range
=====================================

 The JavaScript exception "precision is out of range" occurs when a number that's
 outside of the range of 0 and 20 (or 21) was passed into `toFixed` or
 `toPrecision`.

Message
-------
```

RangeError: toExponential() argument must be between 0 and 100 (V8-based & Safari)
RangeError: toFixed() digits argument must be between 0 and 100 (V8-based & Safari)
RangeError: toPrecision() argument must be between 1 and 100 (V8-based & Safari)
RangeError: precision -1 out of range (Firefox)
```

Error type
----------

`RangeError`What went wrong?
----------------

There was an out of range precision argument in one of these methods:

* `Number.prototype.toExponential()`, which requires the arguments to be between 0 and 100, inclusive.
* `Number.prototype.toFixed()`, which requires the arguments to be between 0 and 100, inclusive.
* `Number.prototype.toPrecision()`, which requires the arguments to be between 1 and 100, inclusive.
Examples
--------

### Invalid cases

```js
(77.1234).toExponential(-1); // RangeError
(77.1234).toExponential(101); // RangeError

(2.34).toFixed(-100); // RangeError
(2.34).toFixed(1001); // RangeError

(1234.5).toPrecision(-1); // RangeError
(1234.5).toPrecision(101); // RangeError
```

### Valid cases

```js
(77.1234).toExponential(4); // 7.7123e+1
(77.1234).toExponential(2); // 7.71e+1

(2.34).toFixed(1); // 2.3
(2.35).toFixed(1); // 2.4 (note that it rounds up in this case)

(5.123456).toPrecision(5); // 5.1235
(5.123456).toPrecision(2); // 5.1
(5.123456).toPrecision(1); // 5
```

See also
--------

* `Number.prototype.toExponential()`
* `Number.prototype.toFixed()`
* `Number.prototype.toPrecision()`


ReferenceError: deprecated caller or arguments usage - JavaScript

ReferenceError: deprecated caller or arguments usage
====================================================

 The JavaScript strict mode-only exception
 "deprecated caller or arguments usage" occurs when the
 deprecated `Function.prototype.caller` or `Function.prototype.arguments` properties
 are used.

Message
-------
```

TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them (V8-based & Firefox)
TypeError: 'arguments', 'callee', and 'caller' cannot be accessed in this context. (Safari)
```

Error type
----------

`TypeError` in strict mode only.

What went wrong?
----------------

 In strict mode, the
 `Function.prototype.caller` or `Function.prototype.arguments` properties are used
 and shouldn't be. They are deprecated, because they leak the function caller, are
 non-standard, hard to optimize and potentially a performance-harmful feature.

Examples
--------

### Deprecated function.caller or arguments.callee

`Function.prototype.caller` and
 `arguments.callee`
 are deprecated (see the reference articles for more information).

```js
"use strict";

function myFunc() {
  if (myFunc.caller === null) {
    return "The function was called from the top!";
  } else {
    return `This function's caller was ${myFunc.caller}`;
  }
}

myFunc();
// TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
```

### Function.prototype.arguments

`Function.prototype.arguments` is deprecated (see the reference article for more
 information).

```js
"use strict";

function f(n) {
  g(n - 1);
}

function g(n) {
  console.log(`before: ${g.arguments[0]}`);
  if (n > 0) {
    f(n);
  }
  console.log(`after: ${g.arguments[0]}`);
}

f(2);

console.log(`returned: ${g.arguments}`);
// TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
```

See also
--------

* Deprecated and obsolete features
* Strict mode
* `Function.prototype.arguments`
* `Function.prototype.caller`
* `arguments.callee`


TypeError: 'x' is not iterable - JavaScript

TypeError: 'x' is not iterable
==============================

 The JavaScript exception "is not iterable" occurs when the value which is given as the
 right-hand side of `for...of`,
 as argument of a function such as `Promise.all` or `TypedArray.from`,
 or as the right-hand side of an array destructuring assignment,
 is not an iterable object.

Message
-------
```

TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator)) (V8-based)
TypeError: x is not iterable (Firefox)
TypeError: undefined is not a function (near '...[x]...') (Safari)
```

Error type
----------

`TypeError`What went wrong?
----------------

 The value which is given as the right-hand side of `for...of`,
 or as argument of a function such as `Promise.all` or `TypedArray.from`,
 or as the right-hand side of an array destructuring assignment,
 is not an iterable object.
 An iterable can be a built-in iterable type such as
 `Array`, `String` or `Map`, a generator result, or
 an object implementing the iterable protocol.

Examples
--------

### Array destructuring a non-iterable

```js
const myobj = { arrayOrObjProp1: {}, arrayOrObjProp2: [42] };

const {
  arrayOrObjProp1: [value1],
  arrayOrObjProp2: [value2],
} = myobj; // TypeError: object is not iterable

console.log(value1, value2);
```

The non-iterable might turn to be `undefined` in some runtime environments.

### Iterating over Object properties

 In JavaScript, `Object`s are not iterable unless they implement
 the iterable protocol.
 Therefore, you cannot use `for...of`
 to iterate over the properties of an object.

```js
const obj = { France: "Paris", England: "London" };
for (const p of obj) {
  // …
} // TypeError: obj is not iterable
```

 Instead you have to use `Object.keys` or `Object.entries`, to
 iterate over the properties or entries of an object.

```js
const obj = { France: "Paris", England: "London" };
// Iterate over the property names:
for (const country of Object.keys(obj)) {
  const capital = obj[country];
  console.log(country, capital);
}

for (const [country, capital] of Object.entries(obj)) {
  console.log(country, capital);
}
```

Another option for this use case might be to use a `Map`:

```js
const map = new Map();
map.set("France", "Paris");
map.set("England", "London");
// Iterate over the property names:
for (const country of map.keys()) {
  const capital = map.get(country);
  console.log(country, capital);
}

for (const capital of map.values()) {
  console.log(capital);
}

for (const [country, capital] of map.entries()) {
  console.log(country, capital);
}
```

### Iterating over a generator

Generator functions
 are functions you call to produce an iterable object.

```js
function\* generate(a, b) {
  yield a;
  yield b;
}

for (const x of generate) {
  console.log(x);
} // TypeError: generate is not iterable
```

 When they are not called, the `Function` object corresponding to the
 generator is callable, but not iterable. Calling a generator produces an iterable
 object which will iterate over the values yielded during the execution of the
 generator.

```js
function\* generate(a, b) {
  yield a;
  yield b;
}

for (const x of generate(1, 2)) {
  console.log(x);
}
```

### Iterating over a custom iterable

 Custom iterables can be created by implementing the
 `Symbol.iterator` method. You must be certain that your iterator method
 returns an object which is an iterator, which is to say it must have a next method.

```js
const myEmptyIterable = {
  [Symbol.iterator]() {
    return []; // [] is iterable, but it is not an iterator — it has no next method.
  },
};

Array.from(myEmptyIterable); // TypeError: myEmptyIterable is not iterable
```

Here is a correct implementation:

```js
const myEmptyIterable = {
  [Symbol.iterator]() {
    return [][Symbol.iterator]();
  },
};

Array.from(myEmptyIterable); // []
```

See also
--------

* Iterable protocol
* `Object.keys`
* `Object.entries`
* `Map`
* Generator functions
* for...of


isFinite() - JavaScript

isFinite()
==========

The **`isFinite()`** function determines whether a value is finite, first converting the value to a number if necessary. A finite number is one that's not `NaN` or ±`Infinity`. Because coercion inside the `isFinite()` function can be surprising, you may prefer to use `Number.isFinite()`.

Try it
------

Syntax
------

```js
isFinite(value)
```

### Parameters

`value`

The value to be tested.

### Return value

`false` if the given value is `NaN`, `Infinity`, or `-Infinity` after being converted to a number; otherwise, `true`.

Description
-----------

`isFinite()` is a function property of the global object.

When the argument to the `isFinite()` function is not of type Number, the value is first coerced to a number, and the resulting value is then compared against `NaN` and ±Infinity. This is as confusing as the behavior of `isNaN` — for example, `isFinite("1")` is `true`.

`Number.isFinite()` is a more reliable way to test whether a value is a finite number value, because it returns `false` for any non-number input.

Examples
--------

### Using isFinite()

```js
isFinite(Infinity); // false
isFinite(NaN); // false
isFinite(-Infinity); // false

isFinite(0); // true
isFinite(2e64); // true
isFinite(910); // true

// Would've been false with the more robust Number.isFinite():
isFinite(null); // true
isFinite("0"); // true
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-isfinite-number |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Number.isFinite()`
* `Number.NaN`
* `Number.POSITIVE_INFINITY`
* `Number.NEGATIVE_INFINITY`


Atomics - JavaScript

Atomics
=======

The **`Atomics`** namespace object contains static methods for carrying out atomic operations. They are used with `SharedArrayBuffer` and `ArrayBuffer` objects.

Description
-----------

Unlike most global objects, `Atomics` is not a constructor. You cannot use it with the `new` operator or invoke the `Atomics` object as a function. All properties and methods of `Atomics` are static (just like the `Math` object).

### Atomic operations

When memory is shared, multiple threads can read and write the same data in memory. Atomic operations make sure that predictable values are written and read, that operations are finished before the next operation starts and that operations are not interrupted.

### Wait and notify

The `wait()` and `notify()` methods are modeled on Linux futexes ("fast user-space mutex") and provide ways for waiting until a certain condition becomes true and are typically used as blocking constructs.

Static properties
-----------------

`Atomics[@@toStringTag]`

The initial value of the `@@toStringTag` property is the string `"Atomics"`. This property is used in `Object.prototype.toString()`.

Static methods
--------------

`Atomics.add()`

Adds the provided value to the existing value at the specified index of the array. Returns the old value at that index.

`Atomics.and()`

Computes a bitwise AND on the value at the specified index of the array with the provided value. Returns the old value at that index.

`Atomics.compareExchange()`

Stores a value at the specified index of the array, if it equals a value. Returns the old value.

`Atomics.exchange()`

Stores a value at the specified index of the array. Returns the old value.

`Atomics.isLockFree()`

An optimization primitive that can be used to determine whether to use locks or atomic operations. Returns `true` if an atomic operation on arrays of the given element size will be implemented using a hardware atomic operation (as opposed to a lock). Experts only.

`Atomics.load()`

Returns the value at the specified index of the array.

`Atomics.notify()`

Notifies agents that are waiting on the specified index of the array. Returns the number of agents that were notified.

`Atomics.or()`

Computes a bitwise OR on the value at the specified index of the array with the provided value. Returns the old value at that index.

`Atomics.store()`

Stores a value at the specified index of the array. Returns the value.

`Atomics.sub()`

Subtracts a value at the specified index of the array. Returns the old value at that index.

`Atomics.wait()`

Verifies that the specified index of the array still contains a value and sleeps awaiting or times out. Returns either `"ok"`, `"not-equal"`, or `"timed-out"`. If waiting is not allowed in the calling agent then it throws an exception. (Most browsers will not allow `wait()` on the browser's main thread.)

`Atomics.waitAsync()`

Waits asynchronously (i.e. without blocking, unlike `Atomics.wait`) on a shared memory location and returns a `Promise`.

`Atomics.xor()`

Computes a bitwise XOR on the value at the specified index of the array with the provided value. Returns the old value at that index.

Examples
--------

### Using Atomics

```js
const sab = new SharedArrayBuffer(1024);
const ta = new Uint8Array(sab);

ta[0]; // 0
ta[0] = 5; // 5

Atomics.add(ta, 0, 12); // 5
Atomics.load(ta, 0); // 17

Atomics.and(ta, 0, 1); // 17
Atomics.load(ta, 0); // 1

Atomics.compareExchange(ta, 0, 5, 12); // 1
Atomics.load(ta, 0); // 1

Atomics.exchange(ta, 0, 12); // 1
Atomics.load(ta, 0); // 12

Atomics.isLockFree(1); // true
Atomics.isLockFree(2); // true
Atomics.isLockFree(3); // false
Atomics.isLockFree(4); // true

Atomics.or(ta, 0, 1); // 12
Atomics.load(ta, 0); // 13

Atomics.store(ta, 0, 12); // 12

Atomics.sub(ta, 0, 2); // 12
Atomics.load(ta, 0); // 10

Atomics.xor(ta, 0, 1); // 10
Atomics.load(ta, 0); // 11
```

### Waiting and notifying

Given a shared `Int32Array`:

```js
const sab = new SharedArrayBuffer(1024);
const int32 = new Int32Array(sab);
```

A reading thread is sleeping and waiting on location 0 which is expected to be 0. As long as that is true, it will not go on. However, once the writing thread has stored a new value, it will be notified by the writing thread and return the new value (123).

```js
Atomics.wait(int32, 0, 0);
console.log(int32[0]); // 123
```

A writing thread stores a new value and notifies the waiting thread once it has written:

```js
console.log(int32[0]); // 0;
Atomics.store(int32, 0, 123);
Atomics.notify(int32, 0, 1);
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-atomics-object |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `ArrayBuffer`
* JavaScript typed arrays guide
* Web Workers
* Shared Memory – a brief tutorial in the TC39 ecmascript-sharedmem proposal
* A Taste of JavaScript's New Parallel Primitives on hacks.mozilla.org (2016)


BigInt - JavaScript

BigInt
======

Baseline Widely available
-------------------------

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2020.

* Learn more
* See full compatibility
* Report feedback
**`BigInt`** values represent numeric values which are too large to be represented by the `number` primitive.

Description
-----------

A **BigInt value**, also sometimes just called a **BigInt**, is a `bigint` primitive, created by appending `n` to the end of an integer literal, or by calling the `BigInt()` function (without the `new` operator) and giving it an integer value or string value.

```js
const previouslyMaxSafeInteger = 9007199254740991n;

const alsoHuge = BigInt(9007199254740991);
// 9007199254740991n

const hugeString = BigInt("9007199254740991");
// 9007199254740991n

const hugeHex = BigInt("0x1fffffffffffff");
// 9007199254740991n

const hugeOctal = BigInt("0o377777777777777777");
// 9007199254740991n

const hugeBin = BigInt(
  "0b11111111111111111111111111111111111111111111111111111",
);
// 9007199254740991n
```

BigInt values are similar to Number values in some ways, but also differ in a few key matters: A BigInt value cannot be used with methods in the built-in `Math` object and cannot be mixed with a Number value in operations; they must be coerced to the same type. Be careful coercing values back and forth, however, as the precision of a BigInt value may be lost when it is coerced to a Number value.

### Type information

When tested against `typeof`, a BigInt value (`bigint` primitive) will give `"bigint"`:

```js
typeof 1n === "bigint"; // true
typeof BigInt("1") === "bigint"; // true
```

A BigInt value can also be wrapped in an `Object`:

```js
typeof Object(1n) === "object"; // true
```

### Operators

Most operators support BigInts, however most do not permit operands to be of mixed types — both operands must be BigInt or neither:

* Arithmetic operators: `+`, `-`, `*`, `/`, `%`, `**`
* Bitwise operators: `>>`, `<<`, `&`, `|`, `^`, `~`
* Unary negation (`-`)
* Increment/decrement: `++`, `--`

The boolean-returning operators allow mixing numbers and BigInts as operands:

* Relational operators and equality operators: `>`, `<`, `>=`, `<=`, `==`, `!=`, `===`, `!==`
* Logical operators only rely on the truthiness of operands

A couple of operators do not support BigInt at all:

* Unary plus (`+`) cannot be supported due to conflicting usage in asm.js, so it has been left out in order to not break asm.js.
* Unsigned right shift (`>>>`) is the only bitwise operator that's unsupported, as every BigInt value is signed.

Special cases:

* Addition (`+`) involving a string and a BigInt returns a string.
* Division (`/`) truncates fractional components towards zero, since BigInt is unable to represent fractional quantities.

```js
const previousMaxSafe = BigInt(Number.MAX\_SAFE\_INTEGER); // 9007199254740991n
const maxPlusOne = previousMaxSafe + 1n; // 9007199254740992n
const theFuture = previousMaxSafe + 2n; // 9007199254740993n, this works now!
const multi = previousMaxSafe \* 2n; // 18014398509481982n
const subtr = multi - 10n; // 18014398509481972n
const mod = multi % 10n; // 2n
const bigN = 2n \*\* 54n; // 18014398509481984n
bigN \* -1n; // -18014398509481984n
const expected = 4n / 2n; // 2n
const truncated = 5n / 2n; // 2n, not 2.5n
```

### Comparisons

A BigInt value is not strictly equal to a Number value, but it *is* loosely so:

```js
0n === 0; // false
0n == 0; // true
```

A Number value and a BigInt value may be compared as usual:

```js
1n < 2; // true
2n > 1; // true
2 > 2; // false
2n > 2; // false
2n >= 2; // true
```

BigInt values and Number values may be mixed in arrays and sorted:

```js
const mixed = [4n, 6, -12n, 10, 4, 0, 0n];
// [4n, 6, -12n, 10, 4, 0, 0n]

mixed.sort(); // default sorting behavior
// [ -12n, 0, 0n, 10, 4n, 4, 6 ]

mixed.sort((a, b) => a - b);
// won't work since subtraction will not work with mixed types
// TypeError: can't convert BigInt value to Number value

// sort with an appropriate numeric comparator
mixed.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
// [ -12n, 0, 0n, 4n, 4, 6, 10 ]
```

Note that comparisons with `Object`-wrapped BigInt values act as with other objects, only indicating equality when the same object instance is compared:

```js
Object(0n) === 0n; // false
Object(0n) === Object(0n); // false

const o = Object(0n);
o === o; // true
```

Because coercing between Number values and BigInt values can lead to loss of precision, the following are recommended:

* Only use a BigInt value when values greater than 253 are reasonably expected.
* Don't coerce between BigInt values and Number values.
### Conditionals

A BigInt value follows the same conversion rules as Numbers when:

* it is converted to a `Boolean`: via the `Boolean` function;
* when used with logical operators `||`, `&&`, and `!`; or
* within a conditional test like an `if` statement.

Namely, only `0n` is falsy; everything else is truthy.

```js
if (0n) {
  console.log("Hello from the if!");
} else {
  console.log("Hello from the else!");
}
// "Hello from the else!"

0n || 12n; // 12n
0n && 12n; // 0n
Boolean(0n); // false
Boolean(12n); // true
!12n; // false
!0n; // true
```

### Cryptography

The operations supported on BigInt values are not constant-time and are thus open to timing attacks. JavaScript BigInts therefore could be dangerous for use in cryptography without mitigating factors. As a very generic example, an attacker could measure the time difference between `101n ** 65537n` and `17n ** 9999n`, and deduce the magnitude of secrets, such as private keys, based on the time elapsed. If you still have to use BigInts, take a look at the Timing attack FAQ for general advice regarding the issue.

### Use within JSON

Using `JSON.stringify()` with any BigInt value will raise a `TypeError`, as BigInt values aren't serialized in JSON by default. However, `JSON.stringify()` specifically leaves a backdoor for BigInt values: it would try to call the BigInt's `toJSON()` method. (It doesn't do so for any other primitive values.) Therefore, you can implement your own `toJSON()` method (which is one of the few cases where patching built-in objects is not explicitly discouraged):

```js
BigInt.prototype.toJSON = function () {
  return this.toString();
};
```

Instead of throwing, `JSON.stringify()` now produces a string like this:

```js
console.log(JSON.stringify({ a: 1n }));
// {"a":"1"}
```

If you do not wish to patch `BigInt.prototype`, you can use the `replacer` parameter of `JSON.stringify` to serialize BigInt values:

```js
const replacer = (key, value) =>
  typeof value === "bigint" ? value.toString() : value;

const data = {
  number: 1,
  big: 18014398509481982n,
};
const stringified = JSON.stringify(data, replacer);

console.log(stringified);
// {"number":1,"big":"18014398509481982"}
```

If you have JSON data containing values you know will be large integers, you can use the `reviver` parameter of `JSON.parse` to handle them:

```js
const reviver = (key, value) => (key === "big" ? BigInt(value) : value);

const payload = '{"number":1,"big":"18014398509481982"}';
const parsed = JSON.parse(payload, reviver);

console.log(parsed);
// { number: 1, big: 18014398509481982n }
```

**Note:** While it's possible to make the replacer of `JSON.stringify()` generic and properly serialize BigInt values for all objects, the reviver of `JSON.parse()` must be specific to the payload shape you expect, because the serialization is *lossy*: it's not possible to distinguish between a string that represents a BigInt and a normal string.

### BigInt coercion

Many built-in operations that expect BigInts first coerce their arguments to BigInts. The operation can be summarized as follows:

* BigInts are returned as-is.
* `undefined` and `null` throw a `TypeError`.
* `true` turns into `1n`; `false` turns into `0n`.
* Strings are converted by parsing them as if they contain an integer literal. Any parsing failure results in a `SyntaxError`. The syntax is a subset of string numeric literals, where decimal points or exponent indicators are not allowed.
* Numbers throw a `TypeError` to prevent unintended implicit coercion causing loss of precision.
* Symbols throw a `TypeError`.
* Objects are first converted to a primitive by calling their `[@@toPrimitive]()` (with `"number"` as hint), `valueOf()`, and `toString()` methods, in that order. The resulting primitive is then converted to a BigInt.

The best way to achieve nearly the same effect in JavaScript is through the `BigInt()` function: `BigInt(x)` uses the same algorithm to convert `x`, except that Numbers don't throw a `TypeError`, but are converted to BigInts if they are integers.

Note that built-in operations expecting BigInts often truncate the BigInt to a fixed width after coercion. This includes `BigInt.asIntN()`, `BigInt.asUintN()`, and methods of `BigInt64Array` and `BigUint64Array`.

Constructor
-----------

`BigInt()`

Creates a new BigInt value.

Static methods
--------------

`BigInt.asIntN()`

Clamps a BigInt value to a signed integer value, and returns that value.

`BigInt.asUintN()`

Clamps a BigInt value to an unsigned integer value, and returns that value.

Instance properties
-------------------

These properties are defined on `BigInt.prototype` and shared by all `BigInt` instances.

`BigInt.prototype.constructor`

The constructor function that created the instance object. For `BigInt` instances, the initial value is the `BigInt` constructor.

`BigInt.prototype[@@toStringTag]`

The initial value of the `@@toStringTag` property is the string `"BigInt"`. This property is used in `Object.prototype.toString()`. However, because `BigInt` also has its own `toString()` method, this property is not used unless you call `Object.prototype.toString.call()` with a BigInt as `thisArg`.

Instance methods
----------------

`BigInt.prototype.toLocaleString()`

Returns a string with a language-sensitive representation of this BigInt value. Overrides the `Object.prototype.toLocaleString()` method.

`BigInt.prototype.toString()`

Returns a string representing this BigInt value in the specified radix (base). Overrides the `Object.prototype.toString()` method.

`BigInt.prototype.valueOf()`

Returns this BigInt value. Overrides the `Object.prototype.valueOf()` method.

Examples
--------

### Calculating Primes

```js
// Returns true if the passed BigInt value is a prime number
function isPrime(p) {
  for (let i = 2n; i \* i <= p; i++) {
    if (p % i === 0n) return false;
  }
  return true;
}

// Takes a BigInt value as an argument, returns nth prime number as a BigInt value
function nthPrime(nth) {
  let maybePrime = 2n;
  let prime = 0n;

  while (nth >= 0n) {
    if (isPrime(maybePrime)) {
      nth--;
      prime = maybePrime;
    }
    maybePrime++;
  }

  return prime;
}

nthPrime(20n);
// 73n
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-bigint-objects |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Number`
* `Number.MAX_SAFE_INTEGER`


Uint8Array - JavaScript

Uint8Array
==========

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 `TypedArray` class.

Constructor
-----------

`Uint8Array()`

Creates a new `Uint8Array` object.

Static properties
-----------------

*Also inherits static properties from its parent `TypedArray`*.

`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 `TypedArray`*.

Instance properties
-------------------

*Also inherits instance properties from its parent `TypedArray`*.

These properties are defined on `Uint8Array.prototype` and shared by all `Uint8Array` instances.

`Uint8Array.prototype.BYTES_PER_ELEMENT`

Returns a number value of the element size. `1` in the case of a `Uint8Array`.

`Uint8Array.prototype.constructor`

The constructor function that created the instance object. For `Uint8Array` instances, the initial value is the `Uint8Array` constructor.

Instance methods
----------------

*Inherits instance methods from its parent `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
--------------

| Specification |
| --- |
| ECMAScript Language Specification # table-49 |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Uint8Array` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `ArrayBuffer`
* `DataView`


ArrayBuffer - JavaScript

ArrayBuffer
===========

The **`ArrayBuffer`** object is used to represent a generic raw binary data buffer.

It is an array of bytes, often referred to in other languages as a "byte array". You cannot directly manipulate the contents of an `ArrayBuffer`; instead, you create one of the typed array objects or a `DataView` object which represents the buffer in a specific format, and use that to read and write the contents of the buffer.

The `ArrayBuffer()` constructor creates a new `ArrayBuffer` of the given length in bytes. You can also get an array buffer from existing data, for example, from a Base64 string or from a local file.

`ArrayBuffer` is a transferable object.

Description
-----------

### Resizing ArrayBuffers

`ArrayBuffer` objects can be made resizable by including the `maxByteLength` option when calling the `ArrayBuffer()` constructor. You can query whether an `ArrayBuffer` is resizable and what its maximum size is by accessing its `resizable` and `maxByteLength` properties, respectively. You can assign a new size to a resizable `ArrayBuffer` with a `resize()` call. New bytes are initialized to 0.

These features make resizing `ArrayBuffer`s more efficient — otherwise, you have to make a copy of the buffer with a new size. It also gives JavaScript parity with WebAssembly in this regard (Wasm linear memory can be resized with `WebAssembly.Memory.prototype.grow()`).

### Transferring ArrayBuffers

`ArrayBuffer` objects can be transferred between different execution contexts, like Web Workers or Service Workers, using the structured clone algorithm. This is done by passing the `ArrayBuffer` as a transferable object in a call to `Worker.postMessage()` or `ServiceWorker.postMessage()`. In pure JavaScript, you can also transfer the ownership of memory from one `ArrayBuffer` to another using its `transfer()` or `transferToFixedLength()` method.

When an `ArrayBuffer` is transferred, its original copy becomes *detached* — this means it is no longer usable. At any moment, there will only be one copy of the `ArrayBuffer` that actually has access to the underlying memory. Detached buffers have the following behaviors:

* `byteLength` becomes 0 (in both the buffer and the associated typed array views).
* Methods, such as `resize()` and `slice()`, throw a `TypeError` when invoked. The associated typed array views' methods also throw a `TypeError`.

You can check whether an `ArrayBuffer` is detached by its `detached` property.

Constructor
-----------

`ArrayBuffer()`

Creates a new `ArrayBuffer` object.

Static properties
-----------------

`ArrayBuffer[@@species]`

The constructor function that is used to create derived objects.

Static methods
--------------

`ArrayBuffer.isView()`

Returns `true` if `arg` is one of the ArrayBuffer views, such as typed array objects or a `DataView`. Returns `false` otherwise.

Instance properties
-------------------

These properties are defined on `ArrayBuffer.prototype` and shared by all `ArrayBuffer` instances.

`ArrayBuffer.prototype.byteLength`

The size, in bytes, of the `ArrayBuffer`. This is established when the array is constructed and can only be changed using the `ArrayBuffer.prototype.resize()` method if the `ArrayBuffer` is resizable.

`ArrayBuffer.prototype.constructor`

The constructor function that created the instance object. For `ArrayBuffer` instances, the initial value is the `ArrayBuffer` constructor.

`ArrayBuffer.prototype.detached`

Read-only. Returns `true` if the `ArrayBuffer` has been detached (transferred), or `false` if not.

`ArrayBuffer.prototype.maxByteLength`

The read-only maximum length, in bytes, that the `ArrayBuffer` can be resized to. This is established when the array is constructed and cannot be changed.

`ArrayBuffer.prototype.resizable`

Read-only. Returns `true` if the `ArrayBuffer` can be resized, or `false` if not.

`ArrayBuffer.prototype[@@toStringTag]`

The initial value of the `@@toStringTag` property is the string `"ArrayBuffer"`. This property is used in `Object.prototype.toString()`.

Instance methods
----------------

`ArrayBuffer.prototype.resize()`

Resizes the `ArrayBuffer` to the specified size, in bytes.

`ArrayBuffer.prototype.slice()`

Returns a new `ArrayBuffer` whose contents are a copy of this `ArrayBuffer`'s bytes from `begin` (inclusive) up to `end` (exclusive). If either `begin` or `end` is negative, it refers to an index from the end of the array, as opposed to from the beginning.

`ArrayBuffer.prototype.transfer()`

Creates a new `ArrayBuffer` with the same byte content as this buffer, then detaches this buffer.

`ArrayBuffer.prototype.transferToFixedLength()`

Creates a new non-resizable `ArrayBuffer` with the same byte content as this buffer, then detaches this buffer.

Examples
--------

### Creating an ArrayBuffer

In this example, we create a 8-byte buffer with a `Int32Array` view referring to the buffer:

```js
const buffer = new ArrayBuffer(8);
const view = new Int32Array(buffer);
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-arraybuffer-objects |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `ArrayBuffer` in `core-js`
* JavaScript typed arrays guide
* `SharedArrayBuffer`
* RangeError: invalid array length


TypedArray - JavaScript

TypedArray
==========

 A ***TypedArray*** object describes an array-like view of an
 underlying binary data buffer.
 There is no global property named `TypedArray`, nor is there a
 directly visible `TypedArray` constructor. Instead, there are a number of
 different global properties, whose values are typed array constructors for specific
 element types, listed below. On the following pages you will find common properties and
 methods that can be used with any typed array containing elements of any type.

Try it
------

Description
-----------

The `TypedArray` constructor (often referred to as `%TypedArray%` to indicate its "intrinsicness", since it does not correspond to any global exposed to a JavaScript program) serves as the common superclass of all `TypedArray` subclasses. Think about `%TypedArray%` as an "abstract class" providing a common interface of utility methods for all typed array subclasses. This constructor is not directly exposed: there is no global `TypedArray` property. It is only accessible through `Object.getPrototypeOf(Int8Array)` and similar.

When creating an instance of a `TypedArray` subclass (e.g. `Int8Array`), an array buffer is created internally in memory or, if an `ArrayBuffer` object is given as constructor argument, that `ArrayBuffer` is used instead. The buffer address is saved as an internal property of the instance and all the methods of `%TypedArray%.prototype` will set and get values based on that array buffer address.

### TypedArray objects

| Type | Value Range | Size in bytes | Web IDL type |
| --- | --- | --- | --- |
| `Int8Array` | -128 to 127 | 1 | `byte` |
| `Uint8Array` | 0 to 255 | 1 | `octet` |
| `Uint8ClampedArray` | 0 to 255 | 1 | `octet` |
| `Int16Array` | -32768 to 32767 | 2 | `short` |
| `Uint16Array` | 0 to 65535 | 2 | `unsigned short` |
| `Int32Array` | -2147483648 to 2147483647 | 4 | `long` |
| `Uint32Array` | 0 to 4294967295 | 4 | `unsigned long` |
| `Float32Array` | `-3.4e38` to `3.4e38` | 4 | `unrestricted float` |
| `Float64Array` | `-1.8e308` to `1.8e308` | 8 | `unrestricted double` |
| `BigInt64Array` | -263 to 263 - 1 | 8 | `bigint` |
| `BigUint64Array` | 0 to 264 - 1 | 8 | `bigint` |

### Value encoding and normalization

All typed arrays operate on `ArrayBuffer`s, where you can observe the exact byte representation of each element, so how the numbers are encoded in binary format is significant.

* Unsigned integer arrays (`Uint8Array`, `Uint16Array`, `Uint32Array`, and `BigUint64Array`) store the number directly in binary.
* Signed integer arrays (`Int8Array`, `Int16Array`, `Int32Array`, and `BigInt64Array`) store the number using two's complement.
* Floating-point arrays (`Float32Array` and `Float64Array`) store the number using IEEE 754 floating-point format. The `Number` reference has more information about the exact format. JavaScript numbers use double precision floating point format by default, which is the same as `Float64Array`. `Float32Array` uses 23 (instead of 52) bits for the mantissa and 8 (instead of 11) bits for the exponent. Note that the spec requires all `NaN` values to use the same bit encoding, but the exact bit pattern is implementation-dependent.
* `Uint8ClampedArray` is a special case. It stores the number in binary like `Uint8Array` does, but when you store a number outside the range, it *clamps* the number to the range 0 to 255 by mathematical value, instead of truncating the most significant bits.

All typed arrays except `Int8Array`, `Uint8Array`, and `Uint8ClampedArray` store each element using multiple bytes. These bytes can either be ordered from most significant to least significant (big-endian) or from least significant to most significant (little-endian). See Endianness for more explanation. Typed arrays always use the platform's native byte order. If you want to specify the endianness when writing and reading from buffers, you should use a `DataView` instead.

When writing to these typed arrays, values that are outside the representable range are normalized.

* All integer arrays (except `Uint8ClampedArray`) use fixed-width number conversion, which first truncates the decimal part of the number and then takes the lowest bits.
* `Uint8ClampedArray` first clamps the number to the range 0 to 255 (values greater than 255 become 255 and values less than 0 become 0). It then *rounds* (instead of flooring) the result to the nearest integer, with half-to-even; meaning if the number is exactly between two integers, it rounds to the nearest even integer. For example, `0.5` becomes `0`, `1.5` becomes `2`, and `2.5` becomes `2`.
* `Float32Array` performs a "round to even" to convert 64-bit floating point numbers to 32-bit. This is the same algorithm as provided by `Math.fround()`.
### Behavior when viewing a resizable buffer

When a `TypedArray` is created as a view of a resizable buffer, resizing the underlying buffer will have different effects on the size of the `TypedArray` depending on whether the `TypedArray` is constructed as length-tracking.

If a typed array is created without a specific size by omitting the third parameter or passing `undefined`, the typed array will become *length-tracking*, and will automatically resize to fit the underlying `buffer` as the latter is resized:

```js
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });
const float32 = new Float32Array(buffer);

console.log(float32.byteLength); // 8
console.log(float32.length); // 2

buffer.resize(12);

console.log(float32.byteLength); // 12
console.log(float32.length); // 3
```

If a typed array is created with a specific size using the third `length` parameter, it won't resize to contain the `buffer` as the latter is grown:

```js
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });
const float32 = new Float32Array(buffer, 0, 2);

console.log(float32.byteLength); // 8
console.log(float32.length); // 2
console.log(float32[0]); // 0, the initial value

buffer.resize(12);

console.log(float32.byteLength); // 8
console.log(float32.length); // 2
console.log(float32[0]); // 0, the initial value
```

When a `buffer` is shrunk, the viewing typed array may become out of bounds, in which case the typed array's observed size will decrease to 0. This is the only case where a non-length-tracking typed array's length may change.

```js
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });
const float32 = new Float32Array(buffer, 0, 2);

buffer.resize(7);

console.log(float32.byteLength); // 0
console.log(float32.length); // 0
console.log(float32[0]); // undefined
```

If you then grow the `buffer` again to bring the typed array back in bounds, the typed array's size will be restored to its original value.

```js
buffer.resize(8);

console.log(float32.byteLength); // 8
console.log(float32.length); // 2
console.log(float32[0]); // 0 - back in bounds again!
```

The same can happen for length-tracking typed arrays as well, if the buffer is shrunk beyond the `byteOffset`.

```js
const buffer = new ArrayBuffer(8, { maxByteLength: 16 });
const float32 = new Float32Array(buffer, 4);
// float32 is length-tracking, but it only extends from the 4th byte
// to the end of the buffer, so if the buffer is resized to be shorter
// than 4 bytes, the typed array will become out of bounds
buffer.resize(3);
console.log(float32.byteLength); // 0
```

Constructor
-----------

This object cannot be instantiated directly — attempting to construct it with `new` throws a `TypeError`.

```js
new (Object.getPrototypeOf(Int8Array))();
// TypeError: Abstract class TypedArray not directly constructable
```

Instead, you create an instance of a typed array of a particular type, such as an `Int8Array` or a `BigInt64Array`. These objects all have a common syntax for their constructors:

```js
new TypedArray()
new TypedArray(length)
new TypedArray(typedArray)
new TypedArray(object)

new TypedArray(buffer)
new TypedArray(buffer, byteOffset)
new TypedArray(buffer, byteOffset, length)
```

Where `TypedArray` is a constructor for one of the concrete types.

**Note:** All `TypedArray` subclasses' constructors can only be constructed with `new`. Attempting to call one without `new` throws a `TypeError`.

### Parameters

`typedArray`

When called with an instance of a `TypedArray` subclass, the `typedArray` gets copied into a new typed array. For a non-bigint `TypedArray` constructor, the `typedArray` parameter can only be of one of the non-bigint types (such as `Int32Array`). Similarly, for a bigint `TypedArray` constructor (`BigInt64Array` or `BigUint64Array`), the `typedArray` parameter can only be of one of the bigint types. Each value in `typedArray` is converted to the corresponding type of the constructor before being copied into the new array. The length of the new typed array will be same as the length of the `typedArray` argument.

`object`

When called with an object that's not a `TypedArray` instance, a new typed array is created in the same way as the `TypedArray.from()` method.

`length` Optional

When called with a non-object, the parameter will be treated as a number specifying the length of the typed array. An internal array buffer is created in memory, of size `length` multiplied by `BYTES_PER_ELEMENT` bytes, filled with zeros. Omitting all parameters is equivalent to using `0` as `length`.

`buffer`, `byteOffset` Optional, `length` Optional

When called with an `ArrayBuffer` or `SharedArrayBuffer` instance, and optionally a `byteOffset` and a `length` argument, a new typed array view is created that views the specified buffer. The `byteOffset` (in bytes) and `length` (in number of elements, each occupying `BYTES_PER_ELEMENT` bytes) parameters specify the memory range that will be exposed by the typed array view. If both are omitted, all of `buffer` is viewed; if only `length` is omitted, the remainder of `buffer` starting from `byteOffset` is viewed. If `length` is omitted, the typed array becomes length-tracking.

### Exceptions

All `TypeArray` subclass constructors operate in the same way. They would all throw the following exceptions:

`TypeError`

Thrown in one of the following cases:

* A `typedArray` is passed but it is a bigint type while the current constructor is not, or vice versa.
* A `typedArray` is passed but the buffer it's viewing is detached, or a detached `buffer` is directly passed.

`RangeError`

Thrown in one of the following cases:

* The new typed array's length is too large.
* The length of `buffer` (if the `length` parameter is not specified) or `byteOffset` is not an integral multiple of the new typed array's element size.
* `byteOffset` is not a valid array index (an integer between 0 and 253 - 1).
* When creating a view from a buffer, the bounds are outside the buffer. In other words, `byteOffset + length * TypedArray.BYTES_PER_ELEMENT > buffer.byteLength`.

Static properties
-----------------

These properties are defined on the `TypedArray` constructor object and are thus shared by all `TypedArray` subclass constructors.

`TypedArray[@@species]`

The constructor function used to create derived objects.

All `TypedArray` subclasses also have the following static properties:

`TypedArray.BYTES_PER_ELEMENT`

Returns a number value of the element size for the different `TypedArray` objects.

Static methods
--------------

These methods are defined on the `TypedArray` constructor object and are thus shared by all `TypedArray` subclass constructors.

`TypedArray.from()`

Creates a new `TypedArray` from an array-like or iterable object. See also `Array.from()`.

`TypedArray.of()`

Creates a new `TypedArray` with a variable number of arguments. See also `Array.of()`.

Instance properties
-------------------

These properties are defined on `TypedArray.prototype` and shared by all `TypedArray` subclass instances.

`TypedArray.prototype.buffer`

Returns the `ArrayBuffer` referenced by the typed array.

`TypedArray.prototype.byteLength`

Returns the length (in bytes) of the typed array.

`TypedArray.prototype.byteOffset`

Returns the offset (in bytes) of the typed array from the start of its `ArrayBuffer`.

`TypedArray.prototype.constructor`

The constructor function that created the instance object. `TypedArray.prototype.constructor` is the hidden `TypedArray` constructor function, but each typed array subclass also defines its own `constructor` property.

`TypedArray.prototype.length`

Returns the number of elements held in the typed array.

`TypedArray.prototype[@@toStringTag]`

The initial value of the `TypedArray.prototype[@@toStringTag]` property is a getter that returns the same string as the typed array constructor's name. It returns `undefined` if the `this` value is not one of the typed array subclasses. This property is used in `Object.prototype.toString()`. However, because `TypedArray` also has its own `toString()` method, this property is not used unless you call `Object.prototype.toString.call()` with a typed array as `thisArg`.

All `TypedArray` subclasses also have the following instance properties:

`TypedArray.prototype.BYTES_PER_ELEMENT`

Returns a number value of the element size for the different `TypedArray` objects.

Instance methods
----------------

These methods are defined on the `TypedArray` prototype object and are thus shared by all `TypedArray` subclass instances.

`TypedArray.prototype.at()`

Takes an integer value and returns the item at that index. This method allows for negative integers, which count back from the last item.

`TypedArray.prototype.copyWithin()`

Copies a sequence of array elements within the array. See also `Array.prototype.copyWithin()`.

`TypedArray.prototype.entries()`

Returns a new *array iterator* object that contains the key/value pairs for each index in the array. See also `Array.prototype.entries()`.

`TypedArray.prototype.every()`

Tests whether all elements in the array pass the test provided by a function. See also `Array.prototype.every()`.

`TypedArray.prototype.fill()`

Fills all the elements of an array from a start index to an end index with a static value. See also `Array.prototype.fill()`.

`TypedArray.prototype.filter()`

Creates a new array with all of the elements of this array for which the provided filtering function returns `true`. See also `Array.prototype.filter()`.

`TypedArray.prototype.find()`

Returns the first `element` in the array that satisfies a provided testing function, or `undefined` if no appropriate element is found. See also `Array.prototype.find()`.

`TypedArray.prototype.findIndex()`

Returns the first index value in the array that has an element that satisfies a provided testing function, or `-1` if no appropriate element was found. See also `Array.prototype.findIndex()`.

`TypedArray.prototype.findLast()`

Returns the value of the last element in the array that satisfies a provided testing function, or `undefined` if no appropriate element is found. See also `Array.prototype.findLast()`.

`TypedArray.prototype.findLastIndex()`

Returns the index of the last element in the array that satisfies a provided testing function, or `-1` if no appropriate element was found. See also `Array.prototype.findLastIndex()`.

`TypedArray.prototype.forEach()`

Calls a function for each element in the array. See also `Array.prototype.forEach()`.

`TypedArray.prototype.includes()`

Determines whether a typed array includes a certain element, returning `true` or `false` as appropriate. See also `Array.prototype.includes()`.

`TypedArray.prototype.indexOf()`

Returns the first (least) index of an element within the array equal to the specified value, or `-1` if none is found. See also `Array.prototype.indexOf()`.

`TypedArray.prototype.join()`

Joins all elements of an array into a string. See also `Array.prototype.join()`.

`TypedArray.prototype.keys()`

Returns a new array iterator that contains the keys for each index in the array. See also `Array.prototype.keys()`.

`TypedArray.prototype.lastIndexOf()`

Returns the last (greatest) index of an element within the array equal to the specified value, or `-1` if none is found. See also `Array.prototype.lastIndexOf()`.

`TypedArray.prototype.map()`

Creates a new array with the results of calling a provided function on every element in this array. See also `Array.prototype.map()`.

`TypedArray.prototype.reduce()`

Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value. See also `Array.prototype.reduce()`.

`TypedArray.prototype.reduceRight()`

Apply a function against an accumulator and each value of the array (from right-to-left) as to reduce it to a single value. See also `Array.prototype.reduceRight()`.

`TypedArray.prototype.reverse()`

Reverses the order of the elements of an array — the first becomes the last, and the last becomes the first. See also `Array.prototype.reverse()`.

`TypedArray.prototype.set()`

Stores multiple values in the typed array, reading input values from a specified array.

`TypedArray.prototype.slice()`

Extracts a section of an array and returns a new array. See also `Array.prototype.slice()`.

`TypedArray.prototype.some()`

Returns `true` if at least one element in this array satisfies the provided testing function. See also `Array.prototype.some()`.

`TypedArray.prototype.sort()`

Sorts the elements of an array in place and returns the array. See also `Array.prototype.sort()`.

`TypedArray.prototype.subarray()`

Returns a new `TypedArray` from the given start and end element index.

`TypedArray.prototype.toLocaleString()`

Returns a localized string representing the array and its elements. See also `Array.prototype.toLocaleString()`.

`TypedArray.prototype.toReversed()`

Returns a new array with the elements in reversed order, without modifying the original array.

`TypedArray.prototype.toSorted()`

Returns a new array with the elements sorted in ascending order, without modifying the original array.

`TypedArray.prototype.toString()`

Returns a string representing the array and its elements. See also `Array.prototype.toString()`.

`TypedArray.prototype.values()`

Returns a new *array iterator* object that contains the values for each index in the array. See also `Array.prototype.values()`.

`TypedArray.prototype.with()`

Returns a new array with the element at the given index replaced with the given value, without modifying the original array.

`TypedArray.prototype[@@iterator]()`

Returns a new *array iterator* object that contains the values for each index in the array.

Examples
--------

### Property access

 You can reference elements in the array using standard array index syntax (that is,
 using bracket notation). However, getting or setting indexed properties on typed arrays
 will not search in the prototype chain for this property, even when the indices are out
 of bound. Indexed properties will consult the `ArrayBuffer` and will never
 look at object properties. You can still use named properties, just like with all
 objects.

```js
// Setting and getting using standard array syntax
const int16 = new Int16Array(2);
int16[0] = 42;
console.log(int16[0]); // 42

// Indexed properties on prototypes are not consulted (Fx 25)
Int8Array.prototype[20] = "foo";
new Int8Array(32)[20]; // 0
// even when out of bound
Int8Array.prototype[20] = "foo";
new Int8Array(8)[20]; // undefined
// or with negative integers
Int8Array.prototype[-1] = "foo";
new Int8Array(8)[-1]; // undefined

// Named properties are allowed, though (Fx 30)
Int8Array.prototype.foo = "bar";
new Int8Array(32).foo; // "bar"
```

### Cannot be frozen

`TypedArray`s that aren't empty cannot be frozen, as their
 underlying `ArrayBuffer` could be mutated through another
 `TypedArray` view of the buffer. This would mean that the object
 would never genuinely be frozen.

```js
const i8 = Int8Array.of(1, 2, 3);
Object.freeze(i8);
// TypeError: Cannot freeze array buffer views with elements
```

### ByteOffset must be aligned

 When constructing a `TypedArray` as a view onto an
 `ArrayBuffer`, the `byteOffset` argument must be aligned to its
 element size; in other words, the offset must be a multiple of
 `BYTES_PER_ELEMENT`.

```js
const i32 = new Int32Array(new ArrayBuffer(4), 1);
// RangeError: start offset of Int32Array should be a multiple of 4
```

```js
const i32 = new Int32Array(new ArrayBuffer(4), 0);
```

### ByteLength must be aligned

 Like the `byteOffset` parameter, the `byteLength` property of an
 `ArrayBuffer` passed to a `TypedArray`'s constructor
 must be a multiple of the constructor's `BYTES_PER_ELEMENT`.

```js
const i32 = new Int32Array(new ArrayBuffer(3));
// RangeError: byte length of Int32Array should be a multiple of 4
```

```js
const i32 = new Int32Array(new ArrayBuffer(4));
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-typedarray-objects |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of typed arrays in `core-js`
* JavaScript typed arrays guide
* `ArrayBuffer`
* `DataView`
* `TextDecoder`


unescape() - JavaScript

unescape()
==========

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Note:** `unescape()` is a non-standard function implemented by browsers and was only standardized for cross-engine compatibility. It is not required to be implemented by all JavaScript engines and may not work everywhere. Use `decodeURIComponent()` or `decodeURI()` if possible.

The **`unescape()`** function computes a new string in which hexadecimal escape sequences are replaced with the characters that they represent. The escape sequences might be introduced by a function like `escape()`.

Syntax
------

```js
unescape(str)
```

### Parameters

`str`

A string to be decoded.

### Return value

A new string in which certain characters have been unescaped.

Description
-----------

`unescape()` is a function property of the global object.

The `unescape()` function replaces any escape sequence with the character that it represents. Specifically, it replaces any escape sequence of the form `%XX` or `%uXXXX` (where `X` represents one hexadecimal digit) with the character that has the hexadecimal value `XX`/`XXXX`. If the escape sequence is not a valid escape sequence (for example, if `%` is followed by one or no hex digit), it is left as-is.

**Note:** This function was used mostly for URL encoding and is partly based on the escape format in RFC 1738. The `unescape()` function does *not* evaluate escape sequences in string literals. You can replace `\xXX` with `%XX` and `\uXXXX` with `%uXXXX` to get a string that can be handled by `unescape()`.

Examples
--------

### Using unescape()

```js
unescape("abc123"); // "abc123"
unescape("%E4%F6%FC"); // "äöü"
unescape("%u0107"); // "ć"
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-unescape-string |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `unescape` in `core-js`
* `decodeURI`
* `decodeURIComponent`
* `escape`


Promise - JavaScript

Promise
=======

The **`Promise`** object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

To learn about the way promises work and how you can use them, we advise you to read Using promises first.

Description
-----------

A **`Promise`** is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a *promise* to supply the value at some point in the future.

A `Promise` is in one of these states:

* *pending*: initial state, neither fulfilled nor rejected.
* *fulfilled*: meaning that the operation was completed successfully.
* *rejected*: meaning that the operation failed.

 The *eventual state* of a pending promise can either be *fulfilled* with a value or *rejected* with a reason (error).
 When either of these options occur, the associated handlers queued up by a promise's `then` method are called. If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached.

A promise is said to be *settled* if it is either fulfilled or rejected, but not pending.

![Flowchart showing how the Promise state transitions between pending, fulfilled, and rejected via then/catch handlers. A pending promise can become either fulfilled or rejected. If fulfilled, the "on fulfillment" handler, or first parameter of the then() method, is executed and carries out further asynchronous actions. If rejected, the error handler, either passed as the second parameter of the then() method or as the sole parameter of the catch() method, gets executed.](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/promises.png)

You will also hear the term *resolved* used with promises — this means that the promise is settled or "locked-in" to match the eventual state of another promise, and further resolving or rejecting it has no effect. The States and fates document from the original Promise proposal contains more details about promise terminology. Colloquially, "resolved" promises are often equivalent to "fulfilled" promises, but as illustrated in "States and fates", resolved promises can be pending or rejected as well. For example:

```js
new Promise((resolveOuter) => {
  resolveOuter(
    new Promise((resolveInner) => {
      setTimeout(resolveInner, 1000);
    }),
  );
});
```

This promise is already *resolved* at the time when it's created (because the `resolveOuter` is called synchronously), but it is resolved with another promise, and therefore won't be *fulfilled* until 1 second later, when the inner promise fulfills. In practice, the "resolution" is often done behind the scenes and not observable, and only its fulfillment or rejection are.

**Note:** Several other languages have mechanisms for lazy evaluation and deferring a computation, which they also call "promises", e.g. Scheme. Promises in JavaScript represent processes that are already happening, which can be chained with callback functions. If you are looking to lazily evaluate an expression, consider using a function with no arguments e.g. `f = () => expression` to create the lazily-evaluated expression, and `f()` to evaluate the expression immediately.

### Chained Promises

The methods `Promise.prototype.then()`, `Promise.prototype.catch()`, and `Promise.prototype.finally()` are used to associate further action with a promise that becomes settled. As these methods return promises, they can be chained.

The `.then()` method takes up to two arguments; the first argument is a callback function for the fulfilled case of the promise, and the second argument is a callback function for the rejected case. Each `.then()` returns a newly generated promise object, which can optionally be used for chaining; for example:

```js
const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("foo");
  }, 300);
});

myPromise
  .then(handleFulfilledA, handleRejectedA)
  .then(handleFulfilledB, handleRejectedB)
  .then(handleFulfilledC, handleRejectedC);
```

Processing continues to the next link of the chain even when a `.then()` lacks a callback function. Therefore, a chain can safely omit every *rejection* callback function until the final `.catch()`.

Handling a rejected promise in each `.then()` has consequences further down the promise chain. Sometimes there is no choice, because an error must be handled immediately. In such cases we must throw an error of some type to maintain error state down the chain. On the other hand, in the absence of an immediate need, it is simpler to leave out error handling until a final `.catch()` statement. A `.catch()` is really just a `.then()` without a slot for a callback function for the case when the promise is fulfilled.

```js
myPromise
  .then(handleFulfilledA)
  .then(handleFulfilledB)
  .then(handleFulfilledC)
  .catch(handleRejectedAny);
```

Using arrow functions for the callback functions, implementation of the promise chain might look something like this:

```js
myPromise
  .then((value) => `${value} and bar`)
  .then((value) => `${value} and bar again`)
  .then((value) => `${value} and again`)
  .then((value) => `${value} and again`)
  .then((value) => {
    console.log(value);
  })
  .catch((err) => {
    console.error(err);
  });
```

**Note:** For faster execution, all synchronous actions should preferably be done within one handler, otherwise it would take several ticks to execute all handlers in sequence.

The termination condition of a promise determines the "settled" state of the next promise in the chain. A "fulfilled" state indicates a successful completion of the promise, while a "rejected" state indicates a lack of success. The return value of each fulfilled promise in the chain is passed along to the next `.then()`, while the reason for rejection is passed along to the next rejection-handler function in the chain.

The promises of a chain are nested in one another, but get popped like the top of a stack. The first promise in the chain is most deeply nested and is the first to pop.
```

(promise D, (promise C, (promise B, (promise A) ) ) )
```

When a `nextValue` is a promise, the effect is a dynamic replacement. The `return` causes a promise to be popped, but the `nextValue` promise is pushed into its place. For the nesting shown above, suppose the `.then()` associated with "promise B" returns a `nextValue` of "promise X". The resulting nesting would look like this:
```

(promise D, (promise C, (promise X) ) )
```

A promise can participate in more than one nesting. For the following code, the transition of `promiseA` into a "settled" state will cause both instances of `.then()` to be invoked.

```js
const promiseA = new Promise(myExecutorFunc);
const promiseB = promiseA.then(handleFulfilled1, handleRejected1);
const promiseC = promiseA.then(handleFulfilled2, handleRejected2);
```

An action can be assigned to an already "settled" promise. In that case, the action (if appropriate) will be performed at the first asynchronous opportunity. Note that promises are guaranteed to be asynchronous. Therefore, an action for an already "settled" promise will occur only after the stack has cleared and a clock-tick has passed. The effect is much like that of `setTimeout(action, 0)`.

```js
const promiseA = new Promise((resolve, reject) => {
  resolve(777);
});
// At this point, "promiseA" is already settled.
promiseA.then((val) => console.log("asynchronous logging has val:", val));
console.log("immediate logging");

// produces output in this order:
// immediate logging
// asynchronous logging has val: 777
```

### Thenables

The JavaScript ecosystem had made multiple Promise implementations long before it became part of the language. Despite being represented differently internally, at the minimum, all Promise-like objects implement the *Thenable* interface. A thenable implements the `.then()` method, which is called with two callbacks: one for when the promise is fulfilled, one for when it's rejected. Promises are thenables as well.

To interoperate with the existing Promise implementations, the language allows using thenables in place of promises. For example, `Promise.resolve` will not only resolve promises, but also trace thenables.

```js
const aThenable = {
  then(onFulfilled, onRejected) {
    onFulfilled({
      // The thenable is fulfilled with another thenable
      then(onFulfilled, onRejected) {
        onFulfilled(42);
      },
    });
  },
};

Promise.resolve(aThenable); // A promise fulfilled with 42
```

### Promise concurrency

The `Promise` class offers four static methods to facilitate async task concurrency:

`Promise.all()`

Fulfills when **all** of the promises fulfill; rejects when **any** of the promises rejects.

`Promise.allSettled()`

Fulfills when **all** promises settle.

`Promise.any()`

Fulfills when **any** of the promises fulfills; rejects when **all** of the promises reject.

`Promise.race()`

Settles when **any** of the promises settles. In other words, fulfills when any of the promises fulfills; rejects when any of the promises rejects.

All these methods take an iterable of promises (thenables, to be exact) and return a new promise. They all support subclassing, which means they can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the `Promise()` constructor — accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. The subclass must also have a `resolve` static method that can be called like `Promise.resolve()` to resolve values to promises.

Note that JavaScript is single-threaded by nature, so at a given instant, only one task will be executing, although control can shift between different promises, making execution of the promises appear concurrent. Parallel execution in JavaScript can only be achieved through worker threads.

Constructor
-----------

`Promise()`

Creates a new `Promise` object. The constructor is primarily used to wrap functions that do not already support promises.

Static properties
-----------------

`Promise[@@species]`

Returns the constructor used to construct return values from promise methods.

Static methods
--------------

`Promise.all()`

Takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input's promises reject, with this first rejection reason.

`Promise.allSettled()`

Takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise.

`Promise.any()`

Takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when any of the input's promises fulfill, with this first fulfillment value. It rejects when all of the input's promises reject (including when an empty iterable is passed), with an `AggregateError` containing an array of rejection reasons.

`Promise.race()`

Takes an iterable of promises as input and returns a single `Promise`. This returned promise settles with the eventual state of the first promise that settles.

`Promise.reject()`

Returns a new `Promise` object that is rejected with the given reason.

`Promise.resolve()`

Returns a `Promise` object that is resolved with the given value. If the value is a thenable (i.e. has a `then` method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise, the returned promise will be fulfilled with the value.

`Promise.withResolvers()`

Returns an object containing a new `Promise` object and two functions to resolve or reject it, corresponding to the two parameters passed to the executor of the `Promise()` constructor.

Instance properties
-------------------

These properties are defined on `Promise.prototype` and shared by all `Promise` instances.

`Promise.prototype.constructor`

The constructor function that created the instance object. For `Promise` instances, the initial value is the `Promise` constructor.

`Promise.prototype[@@toStringTag]`

The initial value of the `@@toStringTag` property is the string `"Promise"`. This property is used in `Object.prototype.toString()`.

Instance methods
----------------

`Promise.prototype.catch()`

Appends a rejection handler callback to the promise, and returns a new promise resolving to the return value of the callback if it is called, or to its original fulfillment value if the promise is instead fulfilled.

`Promise.prototype.finally()`

Appends a handler to the promise, and returns a new promise that is resolved when the original promise is resolved. The handler is called when the promise is settled, whether fulfilled or rejected.

`Promise.prototype.then()`

Appends fulfillment and rejection handlers to the promise, and returns a new promise resolving to the return value of the called handler, or to its original settled value if the promise was not handled (i.e. if the relevant handler `onFulfilled` or `onRejected` is not a function).

Examples
--------

### Basic Example

```js
const myFirstPromise = new Promise((resolve, reject) => {
  // We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed.
  // In this example, we use setTimeout(...) to simulate async code.
  // In reality, you will probably be using something like XHR or an HTML API.
  setTimeout(() => {
    resolve("Success!"); // Yay! Everything went well!
  }, 250);
});

myFirstPromise.then((successMessage) => {
  // successMessage is whatever we passed in the resolve(...) function above.
  // It doesn't have to be a string, but if it is only a succeed message, it probably will be.
  console.log(`Yay! ${successMessage}`);
});
```

### Example with diverse situations

This example shows diverse techniques for using Promise capabilities and diverse situations that can occur. To understand this, start by scrolling to the bottom of the code block, and examine the promise chain. Upon provision of an initial promise, a chain of promises can follow. The chain is composed of `.then()` calls, and typically (but not necessarily) has a single `.catch()` at the end, optionally followed by `.finally()`. In this example, the promise chain is initiated by a custom-written `new Promise()` construct; but in actual practice, promise chains more typically start with an API function (written by someone else) that returns a promise.

The example function `tetheredGetNumber()` shows that a promise generator will utilize `reject()` while setting up an asynchronous call, or within the call-back, or both. The function `promiseGetWord()` illustrates how an API function might generate and return a promise in a self-contained manner.

Note that the function `troubleWithGetNumber()` ends with a `throw`. That is forced because a promise chain goes through all the `.then()` promises, even after an error, and without the `throw`, the error would seem "fixed". This is a hassle, and for this reason, it is common to omit `onRejected` throughout the chain of `.then()` promises, and just have a single `onRejected` in the final `catch()`.

This code can be run under NodeJS. Comprehension is enhanced by seeing the errors actually occur. To force more errors, change the `threshold` values.

```js
// To experiment with error handling, "threshold" values cause errors randomly
const THRESHOLD\_A = 8; // can use zero 0 to guarantee error

function tetheredGetNumber(resolve, reject) {
  setTimeout(() => {
    const randomInt = Date.now();
    const value = randomInt % 10;
    if (value < THRESHOLD\_A) {
      resolve(value);
    } else {
      reject(`Too large: ${value}`);
    }
  }, 500);
}

function determineParity(value) {
  const isOdd = value % 2 === 1;
  return { value, isOdd };
}

function troubleWithGetNumber(reason) {
  const err = new Error("Trouble getting number", { cause: reason });
  console.error(err);
  throw err;
}

function promiseGetWord(parityInfo) {
  return new Promise((resolve, reject) => {
    const { value, isOdd } = parityInfo;
    if (value >= THRESHOLD\_A - 1) {
      reject(`Still too large: ${value}`);
    } else {
      parityInfo.wordEvenOdd = isOdd ? "odd" : "even";
      resolve(parityInfo);
    }
  });
}

new Promise(tetheredGetNumber)
  .then(determineParity, troubleWithGetNumber)
  .then(promiseGetWord)
  .then((info) => {
    console.log(`Got: ${info.value}, ${info.wordEvenOdd}`);
    return info;
  })
  .catch((reason) => {
    if (reason.cause) {
      console.error("Had previously handled error");
    } else {
      console.error(`Trouble with promiseGetWord(): ${reason}`);
    }
  })
  .finally((info) => console.log("All done"));
```

### Advanced Example

This small example shows the mechanism of a `Promise`. The `testPromise()` method is called each time the `<button>` is clicked. It creates a promise that will be fulfilled, using `setTimeout()`, to the promise count (number starting from 1) every 1-3 seconds, at random. The `Promise()` constructor is used to create the promise.

The fulfillment of the promise is logged, via a fulfill callback set using `p1.then()`. A few logs show how the synchronous part of the method is decoupled from the asynchronous completion of the promise.

By clicking the button several times in a short amount of time, you'll even see the different promises being fulfilled one after another.

#### HTML

```html
<button id="make-promise">Make a promise!</button>
<div id="log"></div>
```

#### JavaScript

```js
"use strict";

let promiseCount = 0;

function testPromise() {
  const thisPromiseCount = ++promiseCount;
  const log = document.getElementById("log");
  // begin
  log.insertAdjacentHTML("beforeend", `${thisPromiseCount}) Started<br>`);
  // We make a new promise: we promise a numeric count of this promise,
  // starting from 1 (after waiting 3s)
  const p1 = new Promise((resolve, reject) => {
    // The executor function is called with the ability
    // to resolve or reject the promise
    log.insertAdjacentHTML(
      "beforeend",
      `${thisPromiseCount}) Promise constructor<br>`,
    );
    // This is only an example to create asynchronism
    setTimeout(
      () => {
        // We fulfill the promise
        resolve(thisPromiseCount);
      },
      Math.random() \* 2000 + 1000,
    );
  });

  // We define what to do when the promise is resolved with the then() call,
  // and what to do when the promise is rejected with the catch() call
  p1.then((val) => {
    // Log the fulfillment value
    log.insertAdjacentHTML("beforeend", `${val}) Promise fulfilled<br>`);
  }).catch((reason) => {
    // Log the rejection reason
    console.log(`Handle rejected promise (${reason}) here.`);
  });
  // end
  log.insertAdjacentHTML("beforeend", `${thisPromiseCount}) Promise made<br>`);
}

const btn = document.getElementById("make-promise");
btn.addEventListener("click", testPromise);
```

#### Result

### Loading an image with XHR

Another simple example using `Promise` and `XMLHttpRequest` to load an image is available at the MDN GitHub js-examples repository. You can also see it in action. Each step is commented on and allows you to follow the Promise and XHR architecture closely.

### Incumbent settings object tracking

A settings object is an environment that provides additional information when JavaScript code is running. This includes the realm and module map, as well as HTML specific information such as the origin. The incumbent settings object is tracked in order to ensure that the browser knows which one to use for a given piece of user code.

To better picture this, we can take a closer look at how the realm might be an issue. A **realm** can be roughly thought of as the global object. What is unique about realms is that they hold all of the necessary information to run JavaScript code. This includes objects like `Array` and `Error`. Each settings object has its own "copy" of these and they are not shared. That can cause some unexpected behavior in relation to promises. In order to get around this, we track something called the **incumbent settings object**. This represents information specific to the context of the user code responsible for a certain function call.

To illustrate this a bit further we can take a look at how an `<iframe>` embedded in a document communicates with its host. Since all web APIs are aware of the incumbent settings object, the following will work in all browsers:

```html
<!doctype html> <iframe></iframe>
<!-- we have a realm here -->
<script>
 // we have a realm here as well
 const bound = frames[0].postMessage.bind(frames[0], "some data", "\*");
 // bound is a built-in function — there is no user
 // code on the stack, so which realm do we use?
 setTimeout(bound);
 // this still works, because we use the youngest
 // realm (the incumbent) on the stack
</script>
```

The same concept applies to promises. If we modify the above example a little bit, we get this:

```html
<!doctype html> <iframe></iframe>
<!-- we have a realm here -->
<script>
 // we have a realm here as well
 const bound = frames[0].postMessage.bind(frames[0], "some data", "\*");
 // bound is a built in function — there is no user
 // code on the stack — which realm do we use?
 Promise.resolve(undefined).then(bound);
 // this still works, because we use the youngest
 // realm (the incumbent) on the stack
</script>
```

If we change this so that the `<iframe>` in the document is listening to post messages, we can observe the effect of the incumbent settings object:

```html
<!-- y.html -->
<!doctype html>
<iframe src="x.html"></iframe>
<script>
 const bound = frames[0].postMessage.bind(frames[0], "some data", "\*");
 Promise.resolve(undefined).then(bound);
</script>
```

```html
<!-- x.html -->
<!doctype html>
<script>
 window.addEventListener(
 "message",
 (event) => {
 document.querySelector("#text").textContent = "hello";
 // this code will only run in browsers that track the incumbent settings object
 console.log(event);
 },
 false,
 );
</script>
```

In the above example, the inner text of the `<iframe>` will be updated only if the incumbent settings object is tracked. This is because without tracking the incumbent, we may end up using the wrong environment to send the message.

**Note:** Currently, incumbent realm tracking is fully implemented in Firefox, and has partial implementations in Chrome and Safari.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-promise-objects |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Promise` in `core-js`
* Using promises guide
* Promises/A+ specification
* JavaScript Promises: an introduction on web.dev (2013)
* Callbacks, Promises, and Coroutines: Asynchronous Programming Patterns in JavaScript slide show by Domenic Denicola (2011)


AsyncIterator - JavaScript

AsyncIterator
=============

An **`AsyncIterator`** object is an object that conforms to the async iterator protocol by providing a `next()` method that returns a promise fulfilling to an iterator result object. The `AsyncIterator.prototype` object is a hidden global object that all built-in async iterators inherit from. It provides an `@@asyncIterator` method that returns the async iterator object itself, making the async iterator also async iterable.

Note that `AsyncIterator` is *not* a global object, although it will be in the future with the async iterator helpers proposal. The `AsyncIterator.prototype` object shared by all built-in async iterators can be obtained with the following code:

```js
const AsyncIteratorPrototype = Object.getPrototypeOf(
  Object.getPrototypeOf(Object.getPrototypeOf((async function\* () {})())),
);
```

Description
-----------

Currently, the only built-in JavaScript async iterator is the `AsyncGenerator` object returned by async generator functions. There are some other built-in async iterators in web API, such as the one of a `ReadableStream`.

Each of these async iterators have a distinct prototype object, which defines the `next()` method used by the particular async iterator. All of these prototype objects inherit from `AsyncIterator.prototype`, which provides am `@@asyncIterator` method that returns the async iterator object itself, making the async iterator also async iterable.

**Note:** `AsyncIterator.prototype` does not implement `@@iterator`, so async iterators are not sync iterable by default.

Instance methods
----------------

`AsyncIterator.prototype[@@asyncIterator]()`

Returns the async iterator object itself. This allows async iterator objects to also be async iterable.

Examples
--------

### Using an async iterator as an async iterable

All built-in async iterators are also async iterable, so you can use them in a `for await...of` loop:

```js
const asyncIterator = (async function\* () {
  yield 1;
  yield 2;
  yield 3;
})();
(async () => {
  for await (const value of asyncIterator) {
    console.log(value);
  }
})();
// Logs: 1, 2, 3
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-asynciteratorprototype |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `async function*`
* Iteration protocols


EvalError - JavaScript

EvalError
=========

The **`EvalError`** object indicates an error regarding the global `eval()` function. This exception is not thrown by JavaScript anymore, however the `EvalError` object remains for compatibility.

`EvalError` is a serializable object, so it can be cloned with `structuredClone()` or copied between Workers using `postMessage()`.

`EvalError` is a subclass of `Error`.

Constructor
-----------

`EvalError()`

Creates a new `EvalError` object.

Instance properties
-------------------

*Also inherits instance properties from its parent `Error`*.

These properties are defined on `EvalError.prototype` and shared by all `EvalError` instances.

`EvalError.prototype.constructor`

The constructor function that created the instance object. For `EvalError` instances, the initial value is the `EvalError` constructor.

`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 `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
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-native-error-types-used-in-this-standard-evalerror |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Error`
* `eval()`


JSON - JavaScript

JSON
====

The **`JSON`** namespace object contains static methods for parsing values from and converting values to JavaScript Object Notation (JSON).

Description
-----------

Unlike most global objects, `JSON` is not a constructor. You cannot use it with the `new` operator or invoke the `JSON` object as a function. All properties and methods of `JSON` are static (just like the `Math` object).

### JavaScript and JSON differences

JSON is a syntax for serializing objects, arrays, numbers, strings, booleans, and `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 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 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 `SyntaxError`.

Other differences include allowing only double-quoted strings and no support for `undefined` or comments. For those who wish to use a more human-friendly configuration format based on JSON, there is JSON5, used by the Babel compiler, and the more commonly used 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.

### Full JSON grammar

Valid JSON syntax is formally defined by the following grammar, expressed in ABNF, and copied from IETF JSON standard (RFC):
```

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 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), carriage return (U+000D), line feed (U+000A), and space (U+0020) characters are the only valid whitespace characters.

Static properties
-----------------

`JSON[@@toStringTag]`

The initial value of the `@@toStringTag` property is the string `"JSON"`. This property is used in `Object.prototype.toString()`.

Static methods
--------------

`JSON.parse()`

Parse a piece of string text as JSON, optionally transforming the produced value and its properties, and return the value.

`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 `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
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-json-object |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Date.prototype.toJSON()`
* JSON Diff
* JSON Beautifier/editor
* JSON Parser
* JSON Validator