Number.NaN - JavaScript

Number.NaN
==========

The **`Number.NaN`** static data property represents Not-A-Number, which is equivalent to `NaN`. For more information about the behaviors of `NaN`, see the description for the global property.

Try it
------

Value
-----

The number value `NaN`.

| Property attributes of `Number.NaN` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

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

Because `NaN` is a static property of `Number`, you always use it as `Number.NaN`, rather than as a property of a number value.

Examples
--------

### Checking whether values are numeric

```js
function sanitize(x) {
  if (isNaN(x)) {
    return Number.NaN;
  }
  return x;
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-number.nan |

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

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

See also
--------

* `NaN`
* `Number.isNaN()`


Number.isInteger() - JavaScript

Number.isInteger()
==================

The **`Number.isInteger()`** static method determines whether the passed value is an integer.

Try it
------

Syntax
------

```js
Number.isInteger(value)
```

### Parameters

`value`

The value to be tested for being an integer.

### Return value

The boolean value `true` if the given value is an integer. Otherwise `false`.

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

If the target value is an integer, return `true`, otherwise return `false`. If the value is `NaN` or `Infinity`, return `false`. The method will also return `true` for floating point numbers that can be represented as integer. It will always return `false` if the value is not a number.

Note that some number literals, while looking like non-integers, actually represent integers — due to the precision limit of ECMAScript floating-point number encoding (IEEE-754). For example, `5.0000000000000001` only differs from `5` by `1e-16`, which is too small to be represented. (For reference, `Number.EPSILON` stores the distance between 1 and the next representable floating-point number greater than 1, and that is about `2.22e-16`.) Therefore, `5.0000000000000001` will be represented with the same encoding as `5`, thus making `Number.isInteger(5.0000000000000001)` return `true`.

In a similar sense, numbers around the magnitude of `Number.MAX_SAFE_INTEGER` will suffer from loss of precision and make `Number.isInteger` return `true` even when it's not an integer. (The actual threshold varies based on how many bits are needed to represent the decimal — for example, `Number.isInteger(4500000000000000.1)` is `true`, but `Number.isInteger(4500000000000000.5)` is `false`.)

Examples
--------

### Using isInteger

```js
Number.isInteger(0); // true
Number.isInteger(1); // true
Number.isInteger(-100000); // true
Number.isInteger(99999999999999999999999); // true

Number.isInteger(0.1); // false
Number.isInteger(Math.PI); // false

Number.isInteger(NaN); // false
Number.isInteger(Infinity); // false
Number.isInteger(-Infinity); // false
Number.isInteger("10"); // false
Number.isInteger(true); // false
Number.isInteger(false); // false
Number.isInteger([1]); // false

Number.isInteger(5.0); // true
Number.isInteger(5.000000000000001); // false
Number.isInteger(5.0000000000000001); // true, because of loss of precision
Number.isInteger(4500000000000000.1); // true, because of loss of precision
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-number.isinteger |

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

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

See also
--------

* Polyfill of `Number.isInteger` in `core-js`
* `Number`


Number.prototype.toFixed() - JavaScript

Number.prototype.toFixed()
==========================

The **`toFixed()`** method of `Number` values formats this number using fixed-point notation.

Try it
------

Syntax
------

```js
toFixed()
toFixed(digits)
```

### Parameters

`digits` Optional

The number of digits to appear after the decimal point; should be a value between `0` and `100`, inclusive. If this argument is omitted, it is treated as `0`.

### Return value

A string representing the given number using fixed-point notation.

### Exceptions

`RangeError`

Thrown if `digits` is not between `0` and `100` (inclusive).

`TypeError`

Thrown if this method is invoked on an object that is not a `Number`.

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

The `toFixed()` method returns a string representation of a number without using exponential notation and with exactly `digits` digits after the decimal point. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length.

If the absolute value of the number is greater or equal to 1021, this method uses the same algorithm as `Number.prototype.toString()` and returns a string in exponential notation. `toFixed()` returns `"Infinity"`, `"NaN"`, or `"-Infinity"` if the value of the number is non-finite.

The output of `toFixed()` may be more precise than `toString()` for some values, because `toString()` only prints enough significant digits to distinguish the number from adjacent number values. For example:

```js
(1000000000000000128).toString(); // '1000000000000000100'
(1000000000000000128).toFixed(0); // '1000000000000000128'
```

However, choosing a `digits` precision that's too high can return unexpected results, because decimal fractional numbers cannot be represented precisely in floating point. For example:

```js
(0.3).toFixed(50); // '0.29999999999999998889776975374843459576368331909180'
```

Examples
--------

### Using toFixed()

```js
const numObj = 12345.6789;

numObj.toFixed(); // '12346'; rounding, no fractional part
numObj.toFixed(1); // '12345.7'; it rounds up
numObj.toFixed(6); // '12345.678900'; additional zeros
(1.23e20).toFixed(2); // '123000000000000000000.00'
(1.23e-10).toFixed(2); // '0.00'
(2.34).toFixed(1); // '2.3'
(2.35).toFixed(1); // '2.4'; it rounds up
(2.55).toFixed(1); // '2.5'
// it rounds down as it can't be represented exactly by a float and the
// closest representable float is lower
(2.449999999999999999).toFixed(1); // '2.5'
// it rounds up as it's less than Number.EPSILON away from 2.45.
// This literal actually encodes the same number value as 2.45

(6.02 \* 10 \*\* 23).toFixed(50); // 6.019999999999999e+23; large numbers still use exponential notation
```

### Using toFixed() with negative numbers

Because member access has higher precedence than unary minus, you need to group the negative number expression to get a string.

```js
-2.34.toFixed(1); // -2.3, a number
(-2.34).toFixed(1); // '-2.3'
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-number.prototype.tofixed |

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

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

See also
--------

* `Number.prototype.toExponential()`
* `Number.prototype.toPrecision()`
* `Number.prototype.toString()`
* `Number.EPSILON`


Number.MAX_SAFE_INTEGER - JavaScript

Number.MAX\_SAFE\_INTEGER
=========================

The **`Number.MAX_SAFE_INTEGER`** static data property represents the maximum safe integer in JavaScript (253 – 1).

For larger integers, consider using `BigInt`.

Try it
------

Value
-----

`9007199254740991` (9,007,199,254,740,991, or ~9 quadrillion).

| Property attributes of `Number.MAX_SAFE_INTEGER` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

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

Double precision floating point format only has 52 bits to represent the mantissa, so it can only safely represent integers between -(253 – 1) and 253 – 1. "Safe" in this context refers to the ability to represent integers exactly and to compare them correctly. For example, `Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information.

Because `MAX_SAFE_INTEGER` is a static property of `Number`, you always use it as `Number.MAX_SAFE_INTEGER`, rather than as a property of a number value.

Examples
--------

### Return value of MAX\_SAFE\_INTEGER

```js
Number.MAX\_SAFE\_INTEGER; // 9007199254740991
```

### Relationship between MAX\_SAFE\_INTEGER and EPSILON

`Number.EPSILON` is 2-52, while `MAX_SAFE_INTEGER` is 253 – 1 — both of them are derived from the width of the mantissa, which is 53 bits (with the highest bit always being 1). Multiplying them will give a value very close — but not equal — to 2.

```js
Number.MAX\_SAFE\_INTEGER \* Number.EPSILON; // 1.9999999999999998
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-number.max\_safe\_integer |

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

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

See also
--------

* Polyfill of `Number.MAX_SAFE_INTEGER` in `core-js`
* `Number.MIN_SAFE_INTEGER`
* `Number.isSafeInteger()`
* `BigInt`


Number.prototype.valueOf() - JavaScript

Number.prototype.valueOf()
==========================

The **`valueOf()`** method of `Number` values returns the value of this number.

Try it
------

Syntax
------

```js
valueOf()
```

### Parameters

None.

### Return value

A number representing the primitive value of the specified `Number` object.

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

This method is usually called internally by JavaScript and not explicitly in web code.

Examples
--------

### Using valueOf

```js
const numObj = new Number(10);
console.log(typeof numObj); // object

const num = numObj.valueOf();
console.log(num); // 10
console.log(typeof num); // number
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-number.prototype.valueof |

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

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

See also
--------

* `Object.prototype.valueOf()`


Number.MAX_VALUE - JavaScript

Number.MAX\_VALUE
=================

The **`Number.MAX_VALUE`** static data property represents the maximum numeric value representable in JavaScript.

Try it
------

Value
-----

21024 - 2971, or approximately `1.7976931348623157E+308`.

| Property attributes of `Number.MAX_VALUE` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

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

Values larger than `MAX_VALUE` are represented as `Infinity` and will lose their actual value.

Because `MAX_VALUE` is a static property of `Number`, you always use it as `Number.MAX_VALUE`, rather than as a property of a number value.

Examples
--------

### Using MAX\_VALUE

The following code multiplies two numeric values. If the result is less than or equal to `MAX_VALUE`, the `func1` function is called; otherwise, the `func2` function is called.

```js
if (num1 \* num2 <= Number.MAX\_VALUE) {
  func1();
} else {
  func2();
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-number.max\_value |

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

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

See also
--------

* `Number.MIN_VALUE`
* `Number`


Number.prototype.toString() - JavaScript

Number.prototype.toString()
===========================

The **`toString()`** method of `Number` values returns a string representing this number value.

Try it
------

Syntax
------

```js
toString()
toString(radix)
```

### Parameters

`radix` Optional

An integer in the range `2` through `36` specifying the base to use for representing the number value. Defaults to 10.

### Return value

A string representing the specified number value.

### Exceptions

`RangeError`

Thrown if `radix` is less than 2 or greater than 36.

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

 The `Number` object overrides the `toString` method of `Object`; it does not inherit
 `Object.prototype.toString()`. For `Number` values, the `toString` method returns a string representation of the value in the specified radix.

For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used.

If the specified number value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the number value preceded by a `-` sign, **not** the two's complement of the number value.

Both `0` and `-0` have `"0"` as their string representation. `Infinity` returns `"Infinity"` and `NaN` returns `"NaN"`.

If the number is not a whole number, the decimal point `.` is used to separate the decimal places. Scientific notation is used if the radix is 10 and the number's magnitude (ignoring sign) is greater than or equal to 1021 or less than 10-6. In this case, the returned string always explicitly specifies the sign of the exponent.

```js
console.log((10 \*\* 21.5).toString()); // "3.1622776601683794e+21"
console.log((10 \*\* 21.5).toString(8)); // "526665530627250154000000"
```

The `toString()` method requires its `this` value to be a `Number` primitive or wrapper object. It throws a `TypeError` for other `this` values without attempting to coerce them to number values.

Because `Number` doesn't have a `[@@toPrimitive]()` method, JavaScript calls the `toString()` method automatically when a `Number` *object* is used in a context expecting a string, such as in a template literal. However, Number *primitive* values do not consult the `toString()` method to be coerced to strings — rather, they are directly converted using the same algorithm as the initial `toString()` implementation.

```js
Number.prototype.toString = () => "Overridden";
console.log(`${1}`); // "1"
console.log(`${new Number(1)}`); // "Overridden"
```

Examples
--------

### Using toString()

```js
const count = 10;
console.log(count.toString()); // "10"

console.log((17).toString()); // "17"
console.log((17.2).toString()); // "17.2"

const x = 6;
console.log(x.toString(2)); // "110"
console.log((254).toString(16)); // "fe"
console.log((-10).toString(2)); // "-1010"
console.log((-0xff).toString(2)); // "-11111111"
```

### Converting radix of number strings

If you have a string representing a number in a non-decimal radix, you can use `parseInt()` and `toString()` to convert it to a different radix.

```js
const hex = "CAFEBABE";
const bin = parseInt(hex, 16).toString(2); // "11001010111111101011101010111110"
```

Beware of loss of precision: if the original number string is too large (larger than `Number.MAX_SAFE_INTEGER`, for example), you should use a `BigInt` instead. However, the `BigInt` constructor only has support for strings representing number literals (i.e. strings starting with `0b`, `0o`, `0x`). In case your original radix is not one of binary, octal, decimal, or hexadecimal, you may need to hand-write your radix converter, or use a library.

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-number.prototype.tostring |

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

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

See also
--------

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


Number.isSafeInteger() - JavaScript

Number.isSafeInteger()
======================

The **`Number.isSafeInteger()`** static method determines whether the provided value is a number that is a *safe integer*.

Try it
------

Syntax
------

```js
Number.isSafeInteger(testValue)
```

### Parameters

`testValue`

The value to be tested for being a safe integer.

### Return value

The boolean value `true` if the given value is a number that is a safe integer. Otherwise `false`.

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

The safe integers consist of all integers from -(253 - 1) to 253 - 1, inclusive (±9,007,199,254,740,991). A safe integer is an integer that:

* can be exactly represented as an IEEE-754 double precision number, and
* whose IEEE-754 representation cannot be the result of rounding any other integer to fit the IEEE-754 representation.

For example, 253 - 1 is a safe integer: it can be exactly represented, and no other integer rounds to it under any IEEE-754 rounding mode. In contrast, 253 is *not* a safe integer: it can be exactly represented in IEEE-754, but the integer 253 + 1 can't be directly represented in IEEE-754 but instead rounds to 253 under round-to-nearest and round-to-zero rounding.

Handling values larger or smaller than ~9 quadrillion with full precision requires using an arbitrary precision arithmetic library. See What Every Programmer Needs to Know about Floating Point Arithmetic for more information on floating point representations of numbers.

For larger integers, consider using the `BigInt` type.

Examples
--------

### Using isSafeInteger()

```js
Number.isSafeInteger(3); // true
Number.isSafeInteger(2 \*\* 53); // false
Number.isSafeInteger(2 \*\* 53 - 1); // true
Number.isSafeInteger(NaN); // false
Number.isSafeInteger(Infinity); // false
Number.isSafeInteger("3"); // false
Number.isSafeInteger(3.1); // false
Number.isSafeInteger(3.0); // true
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-number.issafeinteger |

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

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

See also
--------

* Polyfill of `Number.isSafeInteger` in `core-js`
* `Number`
* `Number.MIN_SAFE_INTEGER`
* `Number.MAX_SAFE_INTEGER`
* `BigInt`


Number.parseInt() - JavaScript

Number.parseInt()
=================

 The **`Number.parseInt()`** static method parses a string argument and
 returns an integer of the specified radix or base.

Try it
------

Syntax
------

```js
Number.parseInt(string)
Number.parseInt(string, radix)
```

### Parameters

`string`

The value to parse, coerced to a string. Leading whitespace in this argument is ignored.

`radix` Optional

 An integer between `2` and `36` that represents the
 *radix* (the base in mathematical numeral systems) of the
 `string`.

If `radix` is undefined or `0`, it is assumed to be `10` except when the number begins with the code unit pairs `0x` or `0X`, in which case a radix of `16` is assumed.

### Return value

An integer parsed from the given `string`.

 If the `radix` is smaller than `2` or bigger than
 `36`, or the first non-whitespace character cannot be converted to a number,
 `NaN` is returned.

Examples
--------

### Number.parseInt vs. parseInt

This method has the same functionality as the global `parseInt()` function:

```js
Number.parseInt === parseInt; // true
```

 Its purpose is modularization of globals. Please see
 `parseInt()` for more detail and examples.

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-number.parseint |

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

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

See also
--------

* Polyfill of `Number.parseInt` in `core-js`
* `Number`
* `parseInt()`


AggregateError() constructor - JavaScript

AggregateError() constructor
============================

The **`AggregateError()`** constructor creates `AggregateError` objects.

Syntax
------

```js
new AggregateError(errors)
new AggregateError(errors, message)
new AggregateError(errors, message, options)

AggregateError(errors)
AggregateError(errors, message)
AggregateError(errors, message, options)
```

**Note:** `AggregateError()` can be called with or without `new`. Both create a new `AggregateError` instance.

### Parameters

`errors`

An iterable of errors, may not actually be `Error` instances.

`message` Optional

An optional human-readable description of the aggregate error.

`options` Optional

An object that has the following properties:

`cause` Optional

 A property indicating the specific cause of the error.
 When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error.

Examples
--------

### Creating an AggregateError

```js
try {
  throw new AggregateError([new Error("some error")], "Hello");
} catch (e) {
  console.log(e instanceof AggregateError); // true
  console.log(e.message); // "Hello"
  console.log(e.name); // "AggregateError"
  console.log(e.errors); // [ Error: "some error" ]
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-aggregate-error-constructor |

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

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

See also
--------

* Polyfill of `AggregateError` in `core-js`
* `Promise.any`


AggregateError: errors - JavaScript

AggregateError: errors
======================

The **`errors`** data property of an `AggregateError` instance contains an array representing the errors that were aggregated.

Value
-----

An `Array` containing values in the same order as the iterable passed as the first argument of the `AggregateError()` constructor.

| Property attributes of `AggregateError: errors` |
| --- |
| Writable | yes |
| Enumerable | no |
| Configurable | yes |

Examples
--------

### Using errors

```js
try {
  throw new AggregateError(
    // An iterable of errors
    new Set([new Error("some error"), new Error("another error")]),
    "Multiple errors thrown",
  );
} catch (err) {
  console.log(err.errors);
  // [
  // Error: some error,
  // Error: another error
  // ]
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-aggregate-error |

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

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

See also
--------

* Control flow and error handling guide
* `AggregateError`
* `Error`: `cause`


AsyncGenerator.prototype.return() - JavaScript

AsyncGenerator.prototype.return()
=================================

The **`return()`** method of `AsyncGenerator` instances acts as if a `return` statement is inserted in the generator's body at the current suspended position, which finishes the generator and allows the generator to perform any cleanup tasks when combined with a `try...finally` block.

Syntax
------

```js
asyncGeneratorInstance.return()
asyncGeneratorInstance.return(value)
```

### Parameters

`value` Optional

The value to return.

### Return value

A `Promise` which resolves with an `Object` with two properties:

`done`

A boolean value:

* `true` if the generator function's control flow has reached the end.
* `false` if the generator function's control flow hasn't reached the end and can produce more values. This can only happen if the `return` is captured in a `try...finally` and there are more `yield` expressions in the `finally` block.

`value`

The value that is given as an argument, or, if the `yield` expression is wrapped in a `try...finally`, the value yielded/returned from the `finally` block.

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

The `return()` method, when called, can be seen as if a `return value;` statement is inserted in the generator's body at the current suspended position, where `value` is the value passed to the `return()` method. Therefore, in a typical flow, calling `return(value)` will return `{ done: true, value: value }`. However, if the `yield` expression is wrapped in a `try...finally` block, the control flow doesn't exit the function body, but proceeds to the `finally` block instead. In this case, the value returned may be different, and `done` may even be `false`, if there are more `yield` expressions within the `finally` block.

Examples
--------

### Using return()

The following example shows a simple async generator and the `return` method.

```js
// An async task. Pretend it's doing something more useful
// in practice.
function delayedValue(time, value) {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(value), time);
  });
}

async function\* createAsyncGenerator() {
  yield delayedValue(500, 1);
  yield delayedValue(500, 2);
  yield delayedValue(500, 3);
}

const asyncGen = createAsyncGenerator();
asyncGen.next().then((res) => console.log(res)); // { value: 1, done: false }
asyncGen.return("foo").then((res) => console.log(res)); // { value: "foo", done: true }
asyncGen.next().then((res) => console.log(res)); // { value: undefined, done: true }
```

### Using return() once a generator is complete

If no `value` argument is passed into the `return()` method, the promise will resolve as if the next() method has been called. In this example the generator has completed, so the value returned is `undefined`.

`return()` can still be called after the generator is in a "completed" state, however the generator will stay in this state.

```js
async function\* createAsyncGenerator() {
  yield await Promise.resolve(1);
  yield await Promise.resolve(2);
  yield await Promise.resolve(3);
}
const asyncGen = createAsyncGenerator();
asyncGen.next().then((res) => console.log(res)); // { value: 1, done: false }
asyncGen.next().then((res) => console.log(res)); // { value: 2, done: false }
asyncGen.next().then((res) => console.log(res)); // { value: 3, done: false }
// value is returned undefined, as no value is passed and generator is 'done'
asyncGen.return().then((res) => console.log(res)); // { value: undefined, done: true }
// we can still return a value once the generator is complete
asyncGen.return(1).then((res) => console.log(res)); // { value: 1, done: true }
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-asyncgenerator-prototype-return |

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

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

See also
--------

* `async function*`
* Iterators and generators guide


AsyncGenerator.prototype.next() - JavaScript

AsyncGenerator.prototype.next()
===============================

The **`next()`** method of `AsyncGenerator` instances returns the next value in the sequence.

Syntax
------

```js
next()
next(value)
```

### Parameters

`value` Optional

An optional value used to modify the internal state of the generator. A value passed to the `next()` method will be received by `yield`

### Return value

A `Promise` which when resolved returns an `Object` with two properties:

`done`

A boolean value:

* `true` if the generator is past the end of its control flow. In this case `value` specifies the *return value* of the generator (which may be undefined).
* `false` if the generator is able to produce more values.

`value`

Any JavaScript value yielded or returned by the generator.

Examples
--------

### Using next()

The following example shows a simple generator and the object that the `next` method returns:

```js
// An async task. Pretend it's doing something more useful
// in practice.
function delayedValue(time, value) {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(value), time);
  });
}

async function\* createAsyncGenerator() {
  yield delayedValue(500, 1);
  yield delayedValue(500, 2);
  yield delayedValue(500, 3);
}

const asyncGen = createAsyncGenerator();
asyncGen.next().then((res) => console.log(res)); // { value: 1, done: false }
asyncGen.next().then((res) => console.log(res)); // { value: 2, done: false }
asyncGen.next().then((res) => console.log(res)); // { value: 3, done: false }
asyncGen.next().then((res) => console.log(res)); // { value: undefined, done: true }
```

### Sending values to the generator

In this example, `next` is called with a value.

**Note:** The first call does not log anything, because the generator was not yielding anything initially.

```js
// An async task. Pretend it's doing something more useful
// in practice.
function sleep(time) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, time);
  });
}

async function\* createAsyncGenerator() {
  while (true) {
    await sleep(500);
    const value = yield;
    console.log(value);
  }
}

async function main() {
  const asyncGen = createAsyncGenerator();
  // No log at this step: the first value sent through `next` is lost
  console.log(await asyncGen.next(1)); // { value: undefined, done: false }
  // Logs 2: the value sent through `next`
  console.log(await asyncGen.next(2)); // { value: undefined, done: false }
}

main();
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-asyncgenerator-prototype-next |

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

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

See also
--------

* `async function*`
* Iterators and generators guide


AsyncGenerator.prototype.throw() - JavaScript

AsyncGenerator.prototype.throw()
================================

The **`throw()`** method of `AsyncGenerator` instances acts as if a `throw` statement is inserted in the generator's body at the current suspended position, which informs the generator of an error condition and allows it to handle the error, or perform cleanup and close itself.

Syntax
------

```js
asyncGeneratorInstance.throw(exception)
```

### Parameters

`exception`

The exception to throw. For debugging purposes, it is useful to make it an `instanceof` `Error`.

### Return value

If the thrown error is not caught, it will return a `Promise` which rejects with the exception passed in.

If the exception is caught by a `try...catch` and the generator resumes to yield more values, it will return a `Promise` which resolves with an `Object` with two properties:

`done`

A boolean value:

* `true` if the generator function's control flow has reached the end.
* `false` if the generator function is able to produce more values.

`value`

The value yielded from the next `yield` expression.

Examples
--------

### Using throw()

The following example shows a simple generator and an error that is thrown using the `throw` method. An error can be caught by a `try...catch` block as usual.

```js
// An async task. Pretend it's doing something more useful
// in practice.
function sleep(time) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, time);
  });
}

async function\* createAsyncGenerator() {
  while (true) {
    try {
      await sleep(500);
      yield 42;
    } catch (e) {
      console.error(e);
    }
  }
}

const asyncGen = createAsyncGenerator();
asyncGen.next(1).then((res) => console.log(res)); // { value: 42, done: false }
asyncGen
  .throw(new Error("Something went wrong")) // Error: Something went wrong
  .then((res) => console.log(res)); // { value: 42, done: false }
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-asyncgenerator-prototype-throw |

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

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

See also
--------

* `async function*`
* Iterators and generators guide


DataView.prototype.setInt16() - JavaScript

DataView.prototype.setInt16()
=============================

The **`setInt16()`** method of `DataView` instances takes a number and stores it as a 16-bit signed integer in the 2 bytes starting at the specified byte offset of this `DataView`. There is no alignment constraint; multi-byte values may be stored at any offset within bounds.

Try it
------

Syntax
------

```js
setInt16(byteOffset, value)
setInt16(byteOffset, value, littleEndian)
```

### Parameters

`byteOffset`

The offset, in bytes, from the start of the view to store the data in.

`value`

The value to set. For how the value is encoded in bytes, see Value encoding and normalization.

`littleEndian` Optional

Indicates whether the data is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written.

### Return value

`undefined`.

### Exceptions

`RangeError`

Thrown if the `byteOffset` is set such that it would store beyond the end of the view.

Examples
--------

### Using setInt16()

```js
const buffer = new ArrayBuffer(10);
const dataview = new DataView(buffer);
dataview.setInt16(0, 3);
dataview.getInt16(1); // 768
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-dataview.prototype.setint16 |

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

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

See also
--------

* JavaScript typed arrays guide
* `DataView`
* `ArrayBuffer`
* `Int16Array`


DataView.prototype.setFloat32() - JavaScript

DataView.prototype.setFloat32()
===============================

The **`setFloat32()`** method of `DataView` instances takes a number and stores it as a 32-bit floating point number in the 4 bytes starting at the specified byte offset of this `DataView`. There is no alignment constraint; multi-byte values may be stored at any offset within bounds.

Try it
------

Syntax
------

```js
setFloat32(byteOffset, value)
setFloat32(byteOffset, value, littleEndian)
```

### Parameters

`byteOffset`

The offset, in bytes, from the start of the view to store the data in.

`value`

The value to set. For how the value is encoded in bytes, see Value encoding and normalization.

`littleEndian` Optional

Indicates whether the data is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written.

### Return value

`undefined`.

### Exceptions

`RangeError`

Thrown if the `byteOffset` is set such that it would store beyond the end of the view.

Examples
--------

### Using setFloat32()

```js
const buffer = new ArrayBuffer(10);
const dataview = new DataView(buffer);
dataview.setFloat32(0, 3);
dataview.getFloat32(1); // 2
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-dataview.prototype.setfloat32 |

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

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

See also
--------

* JavaScript typed arrays guide
* `DataView`
* `ArrayBuffer`
* `Float32Array`


DataView.prototype.getUint8() - JavaScript

DataView.prototype.getUint8()
=============================

The **`getUint8()`** method of `DataView` instances reads 1 byte at the specified byte offset of this `DataView` and interprets it as an 8-bit unsigned integer.

Try it
------

Syntax
------

```js
getUint8(byteOffset)
```

### Parameters

`byteOffset`

The offset, in bytes, from the start of the view to read the data from.

### Return value

An integer from 0 to 255, inclusive.

### Exceptions

`RangeError`

Thrown if the `byteOffset` is set such that it would read beyond the end of the view.

Examples
--------

### Using getUint8()

```js
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const dataview = new DataView(buffer);
console.log(dataview.getUint8(1)); // 1
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-dataview.prototype.getuint8 |

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

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

See also
--------

* JavaScript typed arrays guide
* `DataView`
* `ArrayBuffer`
* `Uint8Array`


DataView.prototype.setUint16() - JavaScript

DataView.prototype.setUint16()
==============================

The **`setUint16()`** method of `DataView` instances takes a number and stores it as a 16-bit unsigned integer in the 2 bytes starting at the specified byte offset of this `DataView`. There is no alignment constraint; multi-byte values may be stored at any offset within bounds.

Try it
------

Syntax
------

```js
setUint16(byteOffset, value)
setUint16(byteOffset, value, littleEndian)
```

### Parameters

`byteOffset`

The offset, in bytes, from the start of the view to store the data in.

`value`

The value to set. For how the value is encoded in bytes, see Value encoding and normalization.

`littleEndian` Optional

Indicates whether the data is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written.

### Return value

`undefined`.

### Exceptions

`RangeError`

Thrown if the `byteOffset` is set such that it would store beyond the end of the view.

Examples
--------

### Using setUint16()

```js
const buffer = new ArrayBuffer(10);
const dataview = new DataView(buffer);
dataview.setUint16(0, 3);
dataview.getUint16(1); // 768
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-dataview.prototype.setuint16 |

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

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

See also
--------

* JavaScript typed arrays guide
* `DataView`
* `ArrayBuffer`
* `Uint16Array`


DataView.prototype.setBigUint64() - JavaScript

DataView.prototype.setBigUint64()
=================================

The **`setBigUint64()`** method of `DataView` instances takes a BigInt and stores it as a 64-bit unsigned integer in the 8 bytes starting at the specified byte offset of this `DataView`. There is no alignment constraint; multi-byte values may be stored at any offset within bounds.

Try it
------

Syntax
------

```js
setBigUint64(byteOffset, value)
setBigUint64(byteOffset, value, littleEndian)
```

### Parameters

`byteOffset`

The offset, in bytes, from the start of the view to store the data in.

`value`

The value to set as a `BigInt`. For how the value is encoded in bytes, see Value encoding and normalization.

`littleEndian` Optional

Indicates whether the data is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written.

### Return value

`undefined`.

### Exceptions

`RangeError`

Thrown if the `byteOffset` is set such that it would store beyond the end of the view.

Examples
--------

### Using setBigUint64()

```js
const buffer = new ArrayBuffer(10);
const dataview = new DataView(buffer);
dataview.setBigUint64(0, 3n);
dataview.getBigUint64(1); // 768n
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-dataview.prototype.setbiguint64 |

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

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

See also
--------

* JavaScript typed arrays guide
* `DataView`
* `ArrayBuffer`
* `BigUint64Array`


DataView.prototype.getFloat64() - JavaScript

DataView.prototype.getFloat64()
===============================

The **`getFloat64()`** method of `DataView` instances reads 8 bytes starting at the specified byte offset of this `DataView` and interprets them as a 64-bit floating point number. There is no alignment constraint; multi-byte values may be fetched from any offset within bounds.

Try it
------

Syntax
------

```js
getFloat64(byteOffset)
getFloat64(byteOffset, littleEndian)
```

### Parameters

`byteOffset`

The offset, in bytes, from the start of the view to read the data from.

`littleEndian` Optional

Indicates whether the data is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read.

### Return value

Any number value.

### Exceptions

`RangeError`

Thrown if the `byteOffset` is set such that it would read beyond the end of the view.

Examples
--------

### Using getFloat64()

```js
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const dataview = new DataView(buffer);
console.log(dataview.getFloat64(1)); // 8.20788039913184e-304
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-dataview.prototype.getfloat64 |

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

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

See also
--------

* JavaScript typed arrays guide
* `DataView`
* `ArrayBuffer`
* `Float64Array`


DataView.prototype.getFloat32() - JavaScript

DataView.prototype.getFloat32()
===============================

The **`getFloat32()`** method of `DataView` instances reads 4 bytes starting at the specified byte offset of this `DataView` and interprets them as a 32-bit floating point number. There is no alignment constraint; multi-byte values may be fetched from any offset within bounds.

Try it
------

Syntax
------

```js
getFloat32(byteOffset)
getFloat32(byteOffset, littleEndian)
```

### Parameters

`byteOffset`

The offset, in bytes, from the start of the view to read the data from.

`littleEndian` Optional

Indicates whether the data is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read.

### Return value

A floating point number from `-3.4e38` to `3.4e38`.

### Exceptions

`RangeError`

Thrown if the `byteOffset` is set such that it would read beyond the end of the view.

Examples
--------

### Using getFloat32()

```js
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const dataview = new DataView(buffer);
console.log(dataview.getFloat32(1)); // 2.387939260590663e-38
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-dataview.prototype.getfloat32 |

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

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

See also
--------

* JavaScript typed arrays guide
* `DataView`
* `ArrayBuffer`
* `Float32Array`


DataView.prototype.setUint32() - JavaScript

DataView.prototype.setUint32()
==============================

The **`setUint32()`** method of `DataView` instances takes a number and stores it as a 32-bit unsigned integer in the 4 bytes starting at the specified byte offset of this `DataView`. There is no alignment constraint; multi-byte values may be stored at any offset within bounds.

Try it
------

Syntax
------

```js
setUint32(byteOffset, value)
setUint32(byteOffset, value, littleEndian)
```

### Parameters

`byteOffset`

The offset, in bytes, from the start of the view to store the data in.

`value`

The value to set. For how the value is encoded in bytes, see Value encoding and normalization.

`littleEndian` Optional

Indicates whether the data is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written.

### Return value

`undefined`.

### Exceptions

`RangeError`

Thrown if the `byteOffset` is set such that it would store beyond the end of the view.

Examples
--------

### Using setUint32()

```js
const buffer = new ArrayBuffer(10);
const dataview = new DataView(buffer);
dataview.setUint32(0, 3);
dataview.getUint32(1); // 768
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-dataview.prototype.setuint32 |

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

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

See also
--------

* JavaScript typed arrays guide
* `DataView`
* `ArrayBuffer`
* `Uint32Array`


DataView.prototype.setBigInt64() - JavaScript

DataView.prototype.setBigInt64()
================================

The **`setBigInt64()`** method of `DataView` instances takes a BigInt and stores it as a 64-bit signed integer in the 8 bytes starting at the specified byte offset of this `DataView`. There is no alignment constraint; multi-byte values may be stored at any offset within bounds.

Try it
------

Syntax
------

```js
setBigInt64(byteOffset, value)
setBigInt64(byteOffset, value, littleEndian)
```

### Parameters

`byteOffset`

The offset, in bytes, from the start of the view to store the data in.

`value`

The value to set as a `BigInt`. For how the value is encoded in bytes, see Value encoding and normalization.

`littleEndian` Optional

Indicates whether the data is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written.

### Return value

`undefined`.

### Exceptions

`RangeError`

Thrown if the `byteOffset` is set such that it would store beyond the end of the view.

Examples
--------

### Using setBigInt64()

```js
const buffer = new ArrayBuffer(10);
const dataview = new DataView(buffer);
dataview.setBigInt64(0, 3n);
dataview.getBigInt64(1); // 768n
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-dataview.prototype.setbigint64 |

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

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

See also
--------

* JavaScript typed arrays guide
* `DataView`
* `ArrayBuffer`
* `BigInt64Array`


DataView.prototype.setInt32() - JavaScript

DataView.prototype.setInt32()
=============================

The **`setInt32()`** method of `DataView` instances takes a number and stores it as a 32-bit signed integer in the 4 bytes starting at the specified byte offset of this `DataView`. There is no alignment constraint; multi-byte values may be stored at any offset within bounds.

Try it
------

Syntax
------

```js
setInt32(byteOffset, value)
setInt32(byteOffset, value, littleEndian)
```

### Parameters

`byteOffset`

The offset, in bytes, from the start of the view to store the data in.

`value`

The value to set. For how the value is encoded in bytes, see Value encoding and normalization.

`littleEndian` Optional

Indicates whether the data is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written.

### Return value

`undefined`.

### Exceptions

`RangeError`

Thrown if the `byteOffset` is set such that it would store beyond the end of the view.

Examples
--------

### Using setInt32()

```js
const buffer = new ArrayBuffer(10);
const dataview = new DataView(buffer);
dataview.setInt32(0, 3);
dataview.getInt32(1); // 768
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-dataview.prototype.setint32 |

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

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

See also
--------

* JavaScript typed arrays guide
* `DataView`
* `ArrayBuffer`
* `Int32Array`


DataView.prototype.setFloat64() - JavaScript

DataView.prototype.setFloat64()
===============================

The **`setFloat64()`** method of `DataView` instances takes a number and stores it as a 64-bit floating point number in the 8 bytes starting at the specified byte offset of this `DataView`. There is no alignment constraint; multi-byte values may be stored at any offset within bounds.

Try it
------

Syntax
------

```js
setFloat64(byteOffset, value)
setFloat64(byteOffset, value, littleEndian)
```

### Parameters

`byteOffset`

The offset, in bytes, from the start of the view to store the data in.

`value`

The value to set. For how the value is encoded in bytes, see Value encoding and normalization.

`littleEndian` Optional

Indicates whether the data is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is written.

### Return value

`undefined`.

### Exceptions

`RangeError`

Thrown if the `byteOffset` is set such that it would store beyond the end of the view.

Examples
--------

### Using setFloat64()

```js
const buffer = new ArrayBuffer(10);
const dataview = new DataView(buffer);
dataview.setFloat64(0, 3);
dataview.getFloat64(1); // 3.785766995733679e-270
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-dataview.prototype.setfloat64 |

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

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

See also
--------

* JavaScript typed arrays guide
* `DataView`
* `ArrayBuffer`
* `Float64Array`


DataView.prototype.byteOffset - JavaScript

DataView.prototype.byteOffset
=============================

The **`byteOffset`** accessor property of `DataView` instances returns the offset (in bytes) of this view from the start of its `ArrayBuffer` or `SharedArrayBuffer`.

Try it
------

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

The `byteOffset` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed.

Examples
--------

### Using the byteOffset property

```js
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.byteOffset; // 0 (no offset specified)

const dataview2 = new DataView(buffer, 3);
dataview2.byteOffset; // 3 (as specified when constructing the DataView)
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-dataview.prototype.byteoffset |

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

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

See also
--------

* `DataView`
* `ArrayBuffer`
* `SharedArrayBuffer`


DataView.prototype.getInt16() - JavaScript

DataView.prototype.getInt16()
=============================

The **`getInt16()`** method of `DataView` instances reads 2 bytes starting at the specified byte offset of this `DataView` and interprets them as a 16-bit signed integer. There is no alignment constraint; multi-byte values may be fetched from any offset within bounds.

Try it
------

Syntax
------

```js
getInt16(byteOffset)
getInt16(byteOffset, littleEndian)
```

### Parameters

`byteOffset`

The offset, in bytes, from the start of the view to read the data from.

`littleEndian` Optional

Indicates whether the data is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read.

### Return value

An integer from -32768 to 32767, inclusive.

### Exceptions

`RangeError`

Thrown if the `byteOffset` is set such that it would read beyond the end of the view.

Examples
--------

### Using getInt16()

```js
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const dataview = new DataView(buffer);
console.log(dataview.getInt16(1)); // 258
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-dataview.prototype.getint16 |

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

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

See also
--------

* JavaScript typed arrays guide
* `DataView`
* `ArrayBuffer`
* `Int16Array`


DataView() constructor - JavaScript

DataView() constructor
======================

The **`DataView()`** constructor creates `DataView` objects.

Try it
------

Syntax
------

```js
new DataView(buffer)
new DataView(buffer, byteOffset)
new DataView(buffer, byteOffset, byteLength)
```

**Note:** `DataView()` can only be constructed with `new`. Attempting to call it without `new` throws a `TypeError`.

### Parameters

`buffer`

 An existing `ArrayBuffer` or `SharedArrayBuffer` to use as
 the storage backing the new `DataView` object.

`byteOffset` Optional

 The offset, in bytes, to the first byte in the above buffer for the new view to
 reference. If unspecified, the buffer view starts with the first byte.

`byteLength` Optional

 The number of elements in the byte array. If unspecified, the view's length will
 match the buffer's length.

### Return value

A new `DataView` object representing the specified data buffer.

### Exceptions

`RangeError`

Thrown if the `byteOffset` or `byteLength` parameter values result in the view extending past the end of the buffer. In other words, `byteOffset + byteLength > buffer.byteLength`.

Examples
--------

### Using DataView

```js
const buffer = new ArrayBuffer(16);
const view = new DataView(buffer, 0);

view.setInt16(1, 42);
view.getInt16(1); // 42
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-dataview-constructor |

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

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

See also
--------

* Polyfill of `DataView` in `core-js`
* `DataView`


DataView.prototype.setUint8() - JavaScript

DataView.prototype.setUint8()
=============================

The **`setUint8()`** method of `DataView` instances takes a number and stores it as an 8-bit unsigned integer in the byte at the specified byte offset of this `DataView`.

Try it
------

Syntax
------

```js
setUint8(byteOffset, value)
```

### Parameters

`byteOffset`

The offset, in bytes, from the start of the view to store the data in.

`value`

The value to set. For how the value is encoded in bytes, see Value encoding and normalization.

### Return value

`undefined`.

### Exceptions

`RangeError`

Thrown if the `byteOffset` is set such that it would store beyond the end of the view.

Examples
--------

### Using setUint8()

```js
const buffer = new ArrayBuffer(10);
const dataview = new DataView(buffer);
dataview.setUint8(0, 3);
dataview.getUint8(0); // 3
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-dataview.prototype.setuint8 |

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

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

See also
--------

* JavaScript typed arrays guide
* `DataView`
* `ArrayBuffer`
* `Uint8Array`


DataView.prototype.getUint32() - JavaScript

DataView.prototype.getUint32()
==============================

The **`getUint32()`** method of `DataView` instances reads 4 bytes starting at the specified byte offset of this `DataView` and interprets them as a 32-bit unsigned integer. There is no alignment constraint; multi-byte values may be fetched from any offset within bounds.

Try it
------

Syntax
------

```js
getUint32(byteOffset)
getUint32(byteOffset, littleEndian)
```

### Parameters

`byteOffset`

The offset, in bytes, from the start of the view to read the data from.

`littleEndian` Optional

Indicates whether the data is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read.

### Return value

An integer from 0 to 4294967295, inclusive.

### Exceptions

`RangeError`

Thrown if the `byteOffset` is set such that it would read beyond the end of the view.

Examples
--------

### Using getUint32()

```js
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const dataview = new DataView(buffer);
console.log(dataview.getUint32(1)); // 16909060
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-dataview.prototype.getuint32 |

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

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

See also
--------

* JavaScript typed arrays guide
* `DataView`
* `ArrayBuffer`
* `Uint32Array`


DataView.prototype.byteLength - JavaScript

DataView.prototype.byteLength
=============================

The **`byteLength`** accessor property of `DataView` instances returns the length (in bytes) of this view.

Try it
------

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

The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when an `DataView` is constructed and cannot be changed. If the `DataView` is not specifying an offset or a `byteLength`, the `byteLength` of the referenced `ArrayBuffer` or `SharedArrayBuffer` will be returned.

Examples
--------

### Using the byteLength property

```js
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.byteLength; // 8 (matches the byteLength of the buffer)

const dataview2 = new DataView(buffer, 1, 5);
dataview2.byteLength; // 5 (as specified when constructing the DataView)

const dataview3 = new DataView(buffer, 2);
dataview3.byteLength; // 6 (due to the offset of the constructed DataView)
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-dataview.prototype.bytelength |

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

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

See also
--------

* `DataView`
* `ArrayBuffer`
* `SharedArrayBuffer`


DataView.prototype.buffer - JavaScript

DataView.prototype.buffer
=========================

The **`buffer`** accessor property of `DataView` instances returns the `ArrayBuffer` or `SharedArrayBuffer` referenced by this view at construction time.

Try it
------

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

The `buffer` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the `DataView` is constructed and cannot be changed.

Examples
--------

### Using the buffer property

```js
const buffer = new ArrayBuffer(8);
const dataview = new DataView(buffer);
dataview.buffer; // ArrayBuffer { byteLength: 8 }
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-dataview.prototype.buffer |

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

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

See also
--------

* `DataView`
* `ArrayBuffer`
* `SharedArrayBuffer`


DataView.prototype.setInt8() - JavaScript

DataView.prototype.setInt8()
============================

The **`setInt8()`** method of `DataView` instances takes a number and stores it as an 8-bit signed integer in the byte at the specified byte offset of this `DataView`.

Try it
------

Syntax
------

```js
setInt8(byteOffset, value)
```

### Parameters

`byteOffset`

The offset, in bytes, from the start of the view to store the data in.

`value`

The value to set. For how the value is encoded in bytes, see Value encoding and normalization.

### Return value

`undefined`.

### Exceptions

`RangeError`

Thrown if the `byteOffset` is set such that it would store beyond the end of the view.

Examples
--------

### Using setInt8()

```js
const buffer = new ArrayBuffer(10);
const dataview = new DataView(buffer);
dataview.setInt8(0, 3);
dataview.getInt8(0); // 3
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-dataview.prototype.setint8 |

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

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

See also
--------

* JavaScript typed arrays guide
* `DataView`
* `ArrayBuffer`
* `Int8Array`


DataView.prototype.getInt8() - JavaScript

DataView.prototype.getInt8()
============================

The **`getInt8()`** method of `DataView` instances reads 1 byte at the specified byte offset of this `DataView` and interprets it as an 8-bit signed integer.

Try it
------

Syntax
------

```js
getInt8(byteOffset)
```

### Parameters

`byteOffset`

The offset, in bytes, from the start of the view to read the data from.

### Return value

An integer from -128 to 127, inclusive.

### Exceptions

`RangeError`

Thrown if the `byteOffset` is set such that it would read beyond the end of the view.

Examples
--------

### Using getInt8()

```js
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const dataview = new DataView(buffer);
console.log(dataview.getInt8(1)); // 1
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-dataview.prototype.getint8 |

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

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

See also
--------

* JavaScript typed arrays guide
* `DataView`
* `ArrayBuffer`
* `Int8Array`


DataView.prototype.getBigInt64() - JavaScript

DataView.prototype.getBigInt64()
================================

The **`getBigInt64()`** method of `DataView` instances reads 8 bytes starting at the specified byte offset of this `DataView` and interprets them as a 64-bit signed integer. There is no alignment constraint; multi-byte values may be fetched from any offset within bounds.

Try it
------

Syntax
------

```js
getBigInt64(byteOffset)
getBigInt64(byteOffset, littleEndian)
```

### Parameters

`byteOffset`

The offset, in bytes, from the start of the view to read the data from.

`littleEndian` Optional

Indicates whether the data is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read.

### Return value

A `BigInt` from -263 to 263-1, inclusive.

### Exceptions

`RangeError`

Thrown if the `byteOffset` is set such that it would read beyond the end of the view.

Examples
--------

### Using getBigInt64()

```js
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const dataview = new DataView(buffer);
console.log(dataview.getBigInt64(1)); // 72623859790382856n
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-dataview.prototype.getbigint64 |

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

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

See also
--------

* JavaScript typed arrays guide
* `DataView`
* `ArrayBuffer`
* `BigInt64Array`


DataView.prototype.getInt32() - JavaScript

DataView.prototype.getInt32()
=============================

The **`getInt32()`** method of `DataView` instances reads 4 bytes starting at the specified byte offset of this `DataView` and interprets them as a 32-bit signed integer. There is no alignment constraint; multi-byte values may be fetched from any offset within bounds.

Try it
------

Syntax
------

```js
getInt32(byteOffset)
getInt32(byteOffset, littleEndian)
```

### Parameters

`byteOffset`

The offset, in bytes, from the start of the view to read the data from.

`littleEndian` Optional

Indicates whether the data is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read.

### Return value

An integer from -2147483648 to 2147483647, inclusive.

### Exceptions

`RangeError`

Thrown if the `byteOffset` is set such that it would read beyond the end of the view.

Examples
--------

### Using getInt32()

```js
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const dataview = new DataView(buffer);
console.log(dataview.getInt32(1)); // 16909060
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-dataview.prototype.getint32 |

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

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

See also
--------

* JavaScript typed arrays guide
* `DataView`
* `ArrayBuffer`
* `Int32Array`


DataView.prototype.getBigUint64() - JavaScript

DataView.prototype.getBigUint64()
=================================

The **`getBigUint64()`** method of `DataView` instances reads 8 bytes starting at the specified byte offset of this `DataView` and interprets them as a 64-bit unsigned integer. There is no alignment constraint; multi-byte values may be fetched from any offset within bounds.

Try it
------

Syntax
------

```js
getBigUint64(byteOffset)
getBigUint64(byteOffset, littleEndian)
```

### Parameters

`byteOffset`

The offset, in bytes, from the start of the view to read the data from.

`littleEndian` Optional

Indicates whether the data is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read.

### Return value

A `BigInt` from 0 to 264-1, inclusive.

### Exceptions

`RangeError`

Thrown if the `byteOffset` is set such that it would read beyond the end of the view.

Examples
--------

### Using getBigUint64()

```js
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const dataview = new DataView(buffer);
console.log(dataview.getBigUint64(1)); // 72623859790382856n
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-dataview.prototype.getbiguint64 |

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

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

See also
--------

* JavaScript typed arrays guide
* `DataView`
* `ArrayBuffer`
* `BigUint64Array`


DataView.prototype.getUint16() - JavaScript

DataView.prototype.getUint16()
==============================

The **`getUint16()`** method of `DataView` instances reads 2 bytes starting at the specified byte offset of this `DataView` and interprets them as a 16-bit unsigned integer. There is no alignment constraint; multi-byte values may be fetched from any offset within bounds.

Try it
------

Syntax
------

```js
getUint16(byteOffset)
getUint16(byteOffset, littleEndian)
```

### Parameters

`byteOffset`

The offset, in bytes, from the start of the view to read the data from.

`littleEndian` Optional

Indicates whether the data is stored in little- or big-endian format. If `false` or `undefined`, a big-endian value is read.

### Return value

An integer from 0 to 65535, inclusive.

### Exceptions

`RangeError`

Thrown if the `byteOffset` is set such that it would read beyond the end of the view.

Examples
--------

### Using getUint16()

```js
const { buffer } = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const dataview = new DataView(buffer);
console.log(dataview.getUint16(1)); // 258
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-dataview.prototype.getuint16 |

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

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

See also
--------

* JavaScript typed arrays guide
* `DataView`
* `ArrayBuffer`
* `Uint16Array`


Symbol.species - JavaScript

Symbol.species
==============

The **`Symbol.species`** static data property represents the well-known symbol `@@species`. Methods that create copies of an object may look up this symbol on the object for the constructor function to use when creating the copy.

**Warning:** The existence of `@@species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are investigating whether to remove this feature. Avoid relying on it if possible.

Try it
------

Value
-----

The well-known symbol `@@species`.

| Property attributes of `Symbol.species` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

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

The `@@species` accessor property allows subclasses to override the default constructor for objects. This specifies a protocol about how instances should be copied. For example, when you use copying methods of arrays, such as `map()`. the `map()` method uses `instance.constructor[Symbol.species]` to get the constructor for constructing the new array. For more information, see subclassing built-ins.

All built-in implementations of `@@species` return the `this` value, which is the current instance's constructor. This allows copying methods to create instances of derived classes rather than the base class — for example, `map()` will return an array of the same type as the original array.

Examples
--------

### Using species

You might want to return `Array` objects in your derived array class `MyArray`. For example, when using methods such as `map()` that return the default constructor, you want these methods to return a parent `Array` object, instead of the `MyArray` object. The `species` symbol lets you do this:

```js
class MyArray extends Array {
  // Overwrite species to the parent Array constructor
  static get [Symbol.species]() {
    return Array;
  }
}
const a = new MyArray(1, 2, 3);
const mapped = a.map((x) => x \* x);

console.log(mapped instanceof MyArray); // false
console.log(mapped instanceof Array); // true
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-symbol.species |

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

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

See also
--------

* `Array[@@species]`
* `ArrayBuffer[@@species]`
* `Map[@@species]`
* `Promise[@@species]`
* `RegExp[@@species]`
* `Set[@@species]`
* `TypedArray[@@species]`


Symbol.prototype[@@toPrimitive]() - JavaScript

Symbol.prototype[@@toPrimitive]()
=================================

The **`[@@toPrimitive]()`** method of `Symbol` values returns this symbol value.

Syntax
------

```js
symbolValue[Symbol.toPrimitive](hint)
```

### Parameters

`hint`

A string value indicating the primitive value to return. The value is ignored.

### Return value

The primitive value of the specified `Symbol` object.

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

 The `[@@toPrimitive]()` method of `Symbol` returns the primitive
 value of a Symbol object as a Symbol data type. The `hint`
 argument is not used.

 JavaScript calls the `[@@toPrimitive]()` method to convert an object to a
 primitive value. You rarely need to invoke the `[@@toPrimitive]()` method
 yourself; JavaScript automatically invokes it when encountering an object where a
 primitive value is expected.

Examples
--------

### Using @@toPrimitive

```js
const sym = Symbol("example");
sym === sym[Symbol.toPrimitive](); // true
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-symbol.prototype-@@toprimitive |

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

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

See also
--------

* `Symbol.toPrimitive`


Symbol.asyncIterator - JavaScript

Symbol.asyncIterator
====================

The **`Symbol.asyncIterator`** static data property represents the well-known symbol `@@asyncIterator`. The async iterable protocol looks up this symbol for the method that returns the async iterator for an object. In order for an object to be async iterable, it must have an `@@asyncIterator` key.

Try it
------

Value
-----

The well-known symbol `@@asyncIterator`.

| Property attributes of `Symbol.asyncIterator` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

Examples
--------

### User-defined async iterables

You can define your own async iterable by setting the `[Symbol.asyncIterator]` property on an object.

```js
const myAsyncIterable = {
  async \*[Symbol.asyncIterator]() {
    yield "hello";
    yield "async";
    yield "iteration!";
  },
};

(async () => {
  for await (const x of myAsyncIterable) {
    console.log(x);
  }
})();
// Logs:
// "hello"
// "async"
// "iteration!"
```

When creating an API, remember that async iterables are designed to represent something *iterable* — like a stream of data or a list —, not to completely replace callbacks and events in most situations.

### Built-in async iterables

There is no object in the core JavaScript language that is async iterable. Some web APIs, such as `ReadableStream`, have the `Symbol.asyncIterator` method set by default.

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-symbol.asynciterator |

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

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

See also
--------

* Iteration protocols
* for await...of


Symbol.prototype.description - JavaScript

Symbol.prototype.description
============================

The **`description`** accessor property of `Symbol` values returns a string containing the description of this symbol, or `undefined` if the symbol has no description.

Try it
------

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

`Symbol` objects can be created with an optional description which can be used for debugging but not to access the symbol itself. The `Symbol.prototype.description` property can be used to read that description. It is different to `Symbol.prototype.toString()` as it does not contain the enclosing `"Symbol()"` string. See the examples.

Examples
--------

### Using description

```js
Symbol("desc").toString(); // "Symbol(desc)"
Symbol("desc").description; // "desc"
Symbol("").description; // ""
Symbol().description; // undefined

// well-known symbols
Symbol.iterator.toString(); // "Symbol(Symbol.iterator)"
Symbol.iterator.description; // "Symbol.iterator"

// global symbols
Symbol.for("foo").toString(); // "Symbol(foo)"
Symbol.for("foo").description; // "foo"
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-symbol.prototype.description |

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

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

See also
--------

* Polyfill of `Symbol.prototype.description` in `core-js`
* `Symbol.prototype.toString()`


Symbol.isConcatSpreadable - JavaScript

Symbol.isConcatSpreadable
=========================

The **`Symbol.isConcatSpreadable`** static data property represents the well-known symbol `@@isConcatSpreadable`. The `Array.prototype.concat()` method looks up this symbol on each object being concatenated to determine if it should be treated as an array-like object and flattened to its array elements.

Try it
------

Value
-----

The well-known symbol `@@isConcatSpreadable`.

| Property attributes of `Symbol.isConcatSpreadable` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

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

The `@@isConcatSpreadable` symbol (`Symbol.isConcatSpreadable`) can be defined as an own or inherited property and its value is a boolean. It can control behavior for arrays and array-like objects:

* For array objects, the default behavior is to spread (flatten) elements. `Symbol.isConcatSpreadable` can avoid flattening in these cases.
* For array-like objects, the default behavior is no spreading or flattening. `Symbol.isConcatSpreadable` can force flattening in these cases.
Examples
--------

### Arrays

By default, `Array.prototype.concat()` spreads (flattens) arrays into its result:

```js
const alpha = ["a", "b", "c"];
const numeric = [1, 2, 3];

const alphaNumeric = alpha.concat(numeric);

console.log(alphaNumeric); // Result: ['a', 'b', 'c', 1, 2, 3]
```

When setting `Symbol.isConcatSpreadable` to `false`, you can disable the default behavior:

```js
const alpha = ["a", "b", "c"];
const numeric = [1, 2, 3];

numeric[Symbol.isConcatSpreadable] = false;
const alphaNumeric = alpha.concat(numeric);

console.log(alphaNumeric); // Result: ['a', 'b', 'c', [1, 2, 3] ]
```

### Array-like objects

For array-like objects, the default is to not spread. `Symbol.isConcatSpreadable` needs to be set to `true` in order to get a flattened array:

```js
const x = [1, 2, 3];

const fakeArray = {
  [Symbol.isConcatSpreadable]: true,
  length: 2,
  0: "hello",
  1: "world",
};

x.concat(fakeArray); // [1, 2, 3, "hello", "world"]
```

**Note:** The `length` property is used to control the number of object properties to be added. In the above example, `length:2` indicates two properties has to be added.

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-symbol.isconcatspreadable |

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

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

See also
--------

* Polyfill of `Symbol.isConcatSpreadable` in `core-js`
* `Array.prototype.concat()`


Symbol.search - JavaScript

Symbol.search
=============

The **`Symbol.search`** static data property represents the well-known symbol `@@search`. The `String.prototype.search()` method looks up this symbol on its first argument for the method that returns the index within a string that matches the current object.

For more information, see `RegExp.prototype[@@search]()` and `String.prototype.search()`.

Try it
------

Value
-----

The well-known symbol `@@search`.

| Property attributes of `Symbol.search` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

Examples
--------

### Custom string search

```js
class caseInsensitiveSearch {
  constructor(value) {
    this.value = value.toLowerCase();
  }
  [Symbol.search](string) {
    return string.toLowerCase().indexOf(this.value);
  }
}

console.log("foobar".search(new caseInsensitiveSearch("BaR"))); // 3
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-symbol.search |

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

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

See also
--------

* Polyfill of `Symbol.search` in `core-js`
* `Symbol.match`
* `Symbol.matchAll`
* `Symbol.replace`
* `Symbol.split`
* `String.prototype.search()`
* `RegExp.prototype[@@search]()`


Symbol.split - JavaScript

Symbol.split
============

The **`Symbol.split`** static data property represents the well-known symbol `@@split`. The `String.prototype.split()` method looks up this symbol on its first argument for the method that splits a string at the indices that match the current object.

For more information, see`RegExp.prototype[@@split]()` and `String.prototype.split()`.

Try it
------

Value
-----

The well-known symbol `@@split`.

| Property attributes of `Symbol.split` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

Examples
--------

### Custom reverse split

```js
class ReverseSplit {
  [Symbol.split](string) {
    const array = string.split(" ");
    return array.reverse();
  }
}

console.log("Another one bites the dust".split(new ReverseSplit()));
// [ "dust", "the", "bites", "one", "Another" ]
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-symbol.split |

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

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

See also
--------

* Polyfill of `Symbol.split` in `core-js`
* `Symbol.match`
* `Symbol.matchAll`
* `Symbol.replace`
* `Symbol.search`
* `String.prototype.split()`
* `RegExp.prototype[@@split]()`


Symbol.toPrimitive - JavaScript

Symbol.toPrimitive
==================

The **`Symbol.toPrimitive`** static data property represents the well-known symbol `@@toPrimitive`. All type coercion algorithms look up this symbol on objects for the method that accepts a preferred type and returns a primitive representation of the object, before falling back to using the object's `valueOf()` and `toString()` methods.

Try it
------

Value
-----

The well-known symbol `@@toPrimitive`.

| Property attributes of `Symbol.toPrimitive` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

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

With the help of the `Symbol.toPrimitive` property (used as a function value), an object can be converted to a primitive value. The function is called with a string argument `hint`, which specifies the preferred type of the result primitive value. The `hint` argument can be one of `"number"`, `"string"`, and `"default"`.

The `"number"` hint is used by numeric coercion algorithms. The `"string"` hint is used by the string coercion algorithm. The `"default"` hint is used by the primitive coercion algorithm. The `hint` only acts as a weak signal of preference, and the implementation is free to ignore it (as `Symbol.prototype[@@toPrimitive]()` does). The language does not enforce alignment between the `hint` and the result type, although `[@@toPrimitive]()` must return a primitive, or a `TypeError` is thrown.

Objects without the `@@toPrimitive` property are converted to primitives by calling the `valueOf()` and `toString()` methods in different orders, which is explained in more detail in the type coercion section. `@@toPrimitive` allows full control over the primitive conversion process. For example, `Date.prototype[@@toPrimitive]` treats `"default"` as if it's `"string"` and calls `toString()` instead of `valueOf()`. `Symbol.prototype[@@toPrimitive]` ignores the hint and always returns a symbol, which means even in string contexts, `Symbol.prototype.toString()` won't be called, and `Symbol` objects must always be explicitly converted to strings through `String()`.

Examples
--------

### Modifying primitive values converted from an object

Following example describes how `Symbol.toPrimitive` property can modify the primitive value converted from an object.

```js
// An object without Symbol.toPrimitive property.
const obj1 = {};
console.log(+obj1); // NaN
console.log(`${obj1}`); // "[object Object]"
console.log(obj1 + ""); // "[object Object]"

// An object with Symbol.toPrimitive property.
const obj2 = {
  [Symbol.toPrimitive](hint) {
    if (hint === "number") {
      return 10;
    }
    if (hint === "string") {
      return "hello";
    }
    return true;
  },
};
console.log(+obj2); // 10 — hint is "number"
console.log(`${obj2}`); // "hello" — hint is "string"
console.log(obj2 + ""); // "true" — hint is "default"
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-symbol.toprimitive |

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

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

See also
--------

* Polyfill of `Symbol.toPrimitive` in `core-js`
* `Date.prototype[@@toPrimitive]()`
* `Symbol.prototype[@@toPrimitive]()`
* `Object.prototype.toString()`
* `Object.prototype.valueOf()`


Symbol.unscopables - JavaScript

Symbol.unscopables
==================

The **`Symbol.unscopables`** static data property represents the well-known symbol `@@unscopables`. The `with` statement looks up this symbol on the scope object for a property containing a collection of properties that should not become bindings within the `with` environment.

Try it
------

Value
-----

The well-known symbol `@@unscopables`.

| Property attributes of `Symbol.unscopables` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

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

The `@@unscopables` symbol (accessed via `Symbol.unscopables`) can be defined on any object to exclude property names from being exposed as lexical variables in `with` environment bindings. Note that when using strict mode, `with` statements are not available, and this symbol is likely not needed.

Setting a property of the `@@unscopables` object to `true` (or any truthy value) will make the corresponding property of the `with` scope object *unscopable* and therefore won't be introduced to the `with` body scope. Setting a property to `false` (or any falsy value) will make it *scopable* and thus appear as lexical scope variables.

When deciding whether `x` is unscopable, the entire prototype chain of the `@@unscopables` property is looked up for a property called `x`. This means if you declared `@@unscopables` as a plain object, `Object.prototype` properties like `toString` would become unscopable as well, which may cause backward incompatibility for legacy code assuming those properties are normally scoped (see an example below). You are advised to make your custom `@@unscopables` property have `null` as its prototype, like `Array.prototype[@@unscopables]` does.

This protocol is also utilized by DOM APIs, such as `Element.prototype.append()`.

Examples
--------

### Scoping in with statements

The following code works fine in ES5 and below. However, in ECMAScript 2015 and later, the `Array.prototype.keys()` method was introduced. That means that inside a `with` environment, "keys" would now be the method and not the variable. That's why the `@@unscopables` symbol was introduced. A built-in `@@unscopables` setting is implemented as `Array.prototype[@@unscopables]` to prevent some of the Array methods being scoped into the `with` statement.

```js
var keys = [];

with (Array.prototype) {
  keys.push("something");
}
```

### Unscopables in objects

You can also set `@@unscopables` for your own objects.

```js
const obj = {
  foo: 1,
  bar: 2,
  baz: 3,
};

obj[Symbol.unscopables] = {
  // Make the object have `null` prototype to prevent
  // `Object.prototype` methods from being unscopable
  \_\_proto\_\_: null,
  // `foo` will be scopable
  foo: false,
  // `bar` will be unscopable
  bar: true,
  // `baz` is omitted; because `undefined` is falsy, it is also scopable (default)
};

with (obj) {
  console.log(foo); // 1
  console.log(bar); // ReferenceError: bar is not defined
  console.log(baz); // 3
}
```

### Avoid using a non-null-prototype object as @@unscopables

Declaring `@@unscopables` as a plain object without eliminating its prototype may cause subtle bugs. Consider the following code working before `@@unscopables`:

```js
const character = {
  name: "Yoda",
  toString: function () {
    return "Use with statements, you must not";
  },
};

with (character) {
  console.log(name + ' says: "' + toString() + '"'); // Yoda says: "Use with statements, you must not"
}
```

To preserve backward compatibility, you decided to add an `@@unscopables` property when adding more properties to `character`. You may naïvely do it like:

```js
const character = {
  name: "Yoda",
  toString: function () {
    return "Use with statements, you must not";
  },
  student: "Luke",
  [Symbol.unscopables]: {
    // Make `student` unscopable
    student: true,
  },
};
```

However, the code above now breaks:

```js
with (character) {
  console.log(name + ' says: "' + toString() + '"'); // Yoda says: "[object Undefined]"
}
```

This is because when looking up `character[Symbol.unscopables].toString`, it returns `Object.prototype.toString()`, which is a truthy value, thus making the `toString()` call in the `with()` statement reference `globalThis.toString()` instead — and because it's called without a `this`, `this` is `undefined`, making it return `[object Undefined]`.

Even when the method is not overridden by `character`, making it unscopable will change the value of `this`.

```js
const proto = {};
const obj = { \_\_proto\_\_: proto };

with (proto) {
  console.log(isPrototypeOf(obj)); // true; `isPrototypeOf` is scoped and `this` is `proto`
}

proto[Symbol.unscopables] = {};

with (proto) {
  console.log(isPrototypeOf(obj)); // TypeError: Cannot convert undefined or null to object
  // `isPrototypeOf` is unscoped and `this` is undefined
}
```

To fix this, always make sure `@@unscopables` only contains properties you wish to be unscopable, without `Object.prototype` properties.

```js
const character = {
  name: "Yoda",
  toString: function () {
    return "Use with statements, you must not";
  },
  student: "Luke",
  [Symbol.unscopables]: {
    // Make the object have `null` prototype to prevent
    // `Object.prototype` methods from being unscopable
    \_\_proto\_\_: null,
    // Make `student` unscopable
    student: true,
  },
};
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-symbol.unscopables |

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

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

See also
--------

* `Array.prototype[@@unscopables]`
* `with`
* `Element.prototype.append()`


Symbol.for() - JavaScript

Symbol.for()
============

 The **`Symbol.for()`** static method searches for existing symbols
 in a runtime-wide symbol registry with the given key and returns it if found. Otherwise
 a new symbol gets created in the global symbol registry with this key.

Try it
------

Syntax
------

```js
Symbol.for(key)
```

### Parameters

`key`

 String, required. The key for the symbol (and also used for the description of the
 symbol).

### Return value

 An existing symbol with the given key if found; otherwise, a new symbol is created and
 returned.

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

 In contrast to `Symbol()`, the `Symbol.for()` function creates a
 symbol available in a global symbol registry list. `Symbol.for()` does also
 not necessarily create a new symbol on every call, but checks first if a symbol with the
 given `key` is already present in the registry. In that case, that symbol is
 returned. If no symbol with the given key is found, `Symbol.for()` will
 create a new global symbol.

Examples
--------

### Using Symbol.for()

```js
Symbol.for("foo"); // create a new global symbol
Symbol.for("foo"); // retrieve the already created symbol

// Same global symbol, but not locally
Symbol.for("bar") === Symbol.for("bar"); // true
Symbol("bar") === Symbol("bar"); // false

// The key is also used as the description
const sym = Symbol.for("mario");
sym.toString(); // "Symbol(mario)"
```

 To avoid name clashes with your global symbol keys and other (library code) global
 symbols, it might be a good idea to prefix your symbols:

```js
Symbol.for("mdn.foo");
Symbol.for("mdn.bar");
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-symbol.for |

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

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

See also
--------

* `Symbol.keyFor()`


Symbol.keyFor() - JavaScript

Symbol.keyFor()
===============

 The **`Symbol.keyFor()`** static method retrieves a shared symbol
 key from the global symbol registry for the given symbol.

Try it
------

Syntax
------

```js
Symbol.keyFor(sym)
```

### Parameters

`sym`

Symbol, required. The symbol to find a key for.

### Return value

A string representing the key for the given symbol if one is found on the global registry; otherwise, `undefined`.

Examples
--------

### Using keyFor()

```js
const globalSym = Symbol.for("foo"); // create a new global symbol
Symbol.keyFor(globalSym); // "foo"

const localSym = Symbol();
Symbol.keyFor(localSym); // undefined

// well-known symbols are not symbols registered
// in the global symbol registry
Symbol.keyFor(Symbol.iterator); // undefined
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-symbol.keyfor |

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

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

See also
--------

* `Symbol.for()`


Symbol() constructor - JavaScript

Symbol() constructor
====================

The **`Symbol()`** function returns primitive values of type Symbol.

Try it
------

Syntax
------

```js
Symbol()
Symbol(description)
```

**Note:** `Symbol()` can only be called without `new`. Attempting to construct it with `new` throws a `TypeError`.

### Parameters

`description` Optional

 A string. A description of the symbol which can be used for debugging but not to
 access the symbol itself.

Examples
--------

### Creating symbols

 To create a new primitive symbol, you write `Symbol()` with an optional
 string as its description:

```js
const sym1 = Symbol();
const sym2 = Symbol("foo");
const sym3 = Symbol("foo");
```

 The above code creates three new symbols. Note that `Symbol("foo")` does not
 coerce the string `"foo"` into a symbol. It creates a new symbol each time:

```js
Symbol("foo") === Symbol("foo"); // false
```

### new Symbol()

 The following syntax with the `new` operator will throw a
 `TypeError`:

```js
const sym = new Symbol(); // TypeError
```

 This prevents authors from creating an explicit `Symbol` wrapper object
 instead of a new symbol value and might be surprising as creating explicit wrapper
 objects around primitive data types is generally possible (for example,
 `new Boolean`, `new String` and `new Number`).

 If you really want to create a `Symbol` wrapper object, you can use the
 `Object()` function:

```js
const sym = Symbol("foo");
const symObj = Object(sym);
typeof sym; // "symbol"
typeof symObj; // "object"
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-symbol-constructor |

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

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

See also
--------

* Polyfill of `Symbol` in `core-js`


Symbol.hasInstance - JavaScript

Symbol.hasInstance
==================

The **`Symbol.hasInstance`** static data property represents the well-known symbol `@@hasInstance`. The `instanceof` operator looks up this symbol on its right-hand operand for the method used to determine if the constructor object recognizes an object as its instance.

Try it
------

Value
-----

The well-known symbol `@@hasInstance`.

| Property attributes of `Symbol.hasInstance` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

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

The `instanceof` operator uses the following algorithm to calculate the return value of `object instanceof constructor`:

1. If `constructor` has a `@@hasInstance` method, then call it with `object` as the first argument and return the result, coerced to a boolean. Throw a `TypeError` if `constructor` is not an object, or if `constructor[@@hasInstance]` is not one of `null`, `undefined`, or a function.
2. Otherwise, if `constructor` doesn't have a `@@hasInstance` method (`constructor[@@hasInstance]` is `null` or `undefined`), then determine the result using the same algorithm as `Function.prototype[@@hasInstance]`. Throw a `TypeError` if `constructor` is not a function.

Because all functions inherit from `Function.prototype` by default, most of the time, the `Function.prototype[@@hasInstance]` method specifies the behavior of `instanceof` when the right-hand side is a function.

Examples
--------

### Custom instanceof behavior

You could implement your custom `instanceof` behavior like this, for example:

```js
class MyArray {
  static [Symbol.hasInstance](instance) {
    return Array.isArray(instance);
  }
}
console.log([] instanceof MyArray); // true
```

```js
function MyArray() {}
Object.defineProperty(MyArray, Symbol.hasInstance, {
  value(instance) {
    return Array.isArray(instance);
  },
});
console.log([] instanceof MyArray); // true
```

### Checking the instance of an object

Just in the same manner at which you can check if an object is an instance of a class using the `instanceof` keyword, we can also use `Symbol.hasInstance` for such checks.

```js
class Animal {
  constructor() {}
}

const cat = new Animal();

console.log(Animal[Symbol.hasInstance](cat)); // true
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-symbol.hasinstance |

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

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

See also
--------

* `instanceof`
* `Function.prototype[@@hasInstance]()`


Symbol.toStringTag - JavaScript

Symbol.toStringTag
==================

The **`Symbol.toStringTag`** static data property represents the well-known symbol `@@toStringTag`. `Object.prototype.toString()` looks up this symbol on the `this` value for the property containing a string that represents the type of the object.

Try it
------

Value
-----

The well-known symbol `@@toStringTag`.

| Property attributes of `Symbol.toStringTag` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

Examples
--------

### Default tags

Some values do not have `Symbol.toStringTag`, but have special `toString()` representations. For a complete list, see `Object.prototype.toString()`.

```js
Object.prototype.toString.call("foo"); // "[object String]"
Object.prototype.toString.call([1, 2]); // "[object Array]"
Object.prototype.toString.call(3); // "[object Number]"
Object.prototype.toString.call(true); // "[object Boolean]"
Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call(null); // "[object Null]"
// ... and more
```

### Built-in toStringTag symbols

Most built-in objects provide their own `@@toStringTag` property. Almost all built-in objects' `@@toStringTag` property is not writable, not enumerable, and configurable; the exception is `Iterator`, which is writable for compatibility reasons.

For constructor objects like `Promise`, the property is installed on `Constructor.prototype`, so that all instances of the constructor inherit `@@toStringTag` and can be stringified. For non-constructor objects like `Math` and `JSON`, the property is installed as a static property, so that the namespace object itself can be stringified. Sometimes, the constructor also provides its own `toString` method (for example, `Intl.Locale`), in which case the `@@toStringTag` property is only used when you explicitly call `Object.prototype.toString` on it.

```js
Object.prototype.toString.call(new Map()); // "[object Map]"
Object.prototype.toString.call(function\* () {}); // "[object GeneratorFunction]"
Object.prototype.toString.call(Promise.resolve()); // "[object Promise]"
// ... and more
```

### Custom tag with toStringTag

When creating your own class, JavaScript defaults to the "Object" tag:

```js
class ValidatorClass {}

Object.prototype.toString.call(new ValidatorClass()); // "[object Object]"
```

Now, with the help of `toStringTag`, you are able to set your own custom tag:

```js
class ValidatorClass {
  get [Symbol.toStringTag]() {
    return "Validator";
  }
}

Object.prototype.toString.call(new ValidatorClass()); // "[object Validator]"
```

### toStringTag available on all DOM prototype objects

Due to a WebIDL spec change in mid-2020, browsers are adding a `Symbol.toStringTag` property to all DOM prototype objects. For example, to access the `Symbol.toStringTag` property on `HTMLButtonElement`:

```js
const test = document.createElement("button");
test.toString(); // "[object HTMLButtonElement]"
test[Symbol.toStringTag]; // "HTMLButtonElement"
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-symbol.tostringtag |

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

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

See also
--------

* Polyfill of `Symbol.toStringTag` in `core-js`
* `Object.prototype.toString()`