JSON.stringify() - JavaScript

JSON.stringify()
================

The **`JSON.stringify()`** static method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Try it
------

Syntax
------

```js
JSON.stringify(value)
JSON.stringify(value, replacer)
JSON.stringify(value, replacer, space)
```

### Parameters

`value`

The value to convert to a JSON string.

`replacer` Optional

A function that alters the behavior of the stringification process, or an array of strings and numbers that specifies properties of `value` to be included in the output. If `replacer` is an array, all elements in this array that are not strings or numbers (either primitives or wrapper objects), including `Symbol` values, are completely ignored. If `replacer` is anything other than a function or an array (e.g. `null` or not provided), all string-keyed properties of the object are included in the resulting JSON string.

`space` Optional

A string or number that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes.

If this is a number, it indicates the number of space characters to be used as indentation, clamped to 10 (that is, any number greater than `10` is treated as if it were `10`). Values less than 1 indicate that no space should be used.

If this is a string, the string (or the first 10 characters of the string, if it's longer than that) is inserted before every nested object or array.

If `space` is anything other than a string or number (can be either a primitive or a wrapper object) — for example, is `null` or not provided — no white space is used.

### Return value

A JSON string representing the given value, or undefined.

### Exceptions

`TypeError`

Thrown in one of the following cases:

* `value` contains a circular reference.
* A `BigInt` value is encountered.

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

`JSON.stringify()` converts a value to the JSON notation that the value represents. Values are stringified in the following manner:

* `Boolean`, `Number`, `String`, and `BigInt` (obtainable via `Object()`) objects are converted to the corresponding primitive values during stringification, in accordance with the traditional conversion semantics. `Symbol` objects (obtainable via `Object()`) are treated as plain objects.
* Attempting to serialize `BigInt` values will throw. However, if the BigInt has a `toJSON()` method (through monkey patching: `BigInt.prototype.toJSON = ...`), that method can provide the serialization result. This constraint ensures that a proper serialization (and, very likely, its accompanying deserialization) behavior is always explicitly provided by the user.
* `undefined`, `Function`, and `Symbol` values are not valid JSON values. If any such values are encountered during conversion, they are either omitted (when found in an object) or changed to `null` (when found in an array). `JSON.stringify()` can return `undefined` when passing in "pure" values like `JSON.stringify(() => {})` or `JSON.stringify(undefined)`.
* The numbers `Infinity` and `NaN`, as well as the value `null`, are all considered `null`. (But unlike the values in the previous point, they would never be omitted.)
* Arrays are serialized as arrays (enclosed by square brackets). Only array indices between 0 and `length - 1` (inclusive) are serialized; other properties are ignored.
* For other objects:
    + All `Symbol`-keyed properties will be completely ignored, even when using the `replacer` parameter.
    + If the value has a `toJSON()` method, it's responsible to define what data will be serialized. Instead of the object being serialized, the value returned by the `toJSON()` method when called will be serialized. `JSON.stringify()` calls `toJSON` with one parameter, the `key`, which has the same semantic as the `key` parameter of the `replacer` function:
        - if this object is a property value, the property name
        - if it is in an array, the index in the array, as a string
        - if `JSON.stringify()` was directly called on this object, an empty string`Date` objects implement the `toJSON()` method which returns a string (the same as `date.toISOString()`). Thus, they will be stringified as strings.
    + Only enumerable own properties are visited. This means `Map`, `Set`, etc. will become `"{}"`. You can use the `replacer` parameter to serialize them to something more useful.
     Properties are visited using the same algorithm as `Object.keys()`, which has a well-defined order and is stable across implementations. For example, `JSON.stringify` on the same object will always produce the same string, and `JSON.parse(JSON.stringify(obj))` would produce an object with the same key ordering as the original (assuming the object is completely JSON-serializable).
### The replacer parameter

The `replacer` parameter can be either a function or an array.

As an array, its elements indicate the names of the properties in the object that should be included in the resulting JSON string. Only string and number values are taken into account; symbol keys are ignored.

As a function, it takes two parameters: the `key` and the `value` being stringified. The object in which the key was found is provided as the `replacer`'s `this` context.

The `replacer` function is called for the initial object being stringified as well, in which case the `key` is an empty string (`""`). It is then called for each property on the object or array being stringified. Array indices will be provided in its string form as `key`. The current property value will be replaced with the `replacer`'s return value for stringification. This means:

* If you return a number, string, boolean, or `null`, that value is directly serialized and used as the property's value. (Returning a BigInt will throw as well.)
* If you return a `Function`, `Symbol`, or `undefined`, the property is not included in the output.
* If you return any other object, the object is recursively stringified, calling the `replacer` function on each property.

**Note:** When parsing JSON generated with `replacer` functions, you would likely want to use the `reviver` parameter to perform the reverse operation.

Typically, array elements' index would never shift (even when the element is an invalid value like a function, it will become `null` instead of omitted). Using the `replacer` function allows you to control the order of the array elements by returning a different array.

### The space parameter

The `space` parameter may be used to control spacing in the final string.

* If it is a number, successive levels in the stringification will each be indented by this many space characters.
* If it is a string, successive levels will be indented by this string.

Each level of indentation will never be longer than 10. Number values of `space` are clamped to 10, and string values are truncated to 10 characters.

Examples
--------

### Using JSON.stringify

```js
JSON.stringify({}); // '{}'
JSON.stringify(true); // 'true'
JSON.stringify("foo"); // '"foo"'
JSON.stringify([1, "false", false]); // '[1,"false",false]'
JSON.stringify([NaN, null, Infinity]); // '[null,null,null]'
JSON.stringify({ x: 5 }); // '{"x":5}'

JSON.stringify(new Date(1906, 0, 2, 15, 4, 5));
// '"1906-01-02T15:04:05.000Z"'

JSON.stringify({ x: 5, y: 6 });
// '{"x":5,"y":6}'
JSON.stringify([new Number(3), new String("false"), new Boolean(false)]);
// '[3,"false",false]'

// String-keyed array elements are not enumerable and make no sense in JSON
const a = ["foo", "bar"];
a["baz"] = "quux"; // a: [ 0: 'foo', 1: 'bar', baz: 'quux' ]
JSON.stringify(a);
// '["foo","bar"]'

JSON.stringify({ x: [10, undefined, function () {}, Symbol("")] });
// '{"x":[10,null,null,null]}'

// Standard data structures
JSON.stringify([
  new Set([1]),
  new Map([[1, 2]]),
  new WeakSet([{ a: 1 }]),
  new WeakMap([[{ a: 1 }, 2]]),
]);
// '[{},{},{},{}]'

// TypedArray
JSON.stringify([new Int8Array([1]), new Int16Array([1]), new Int32Array([1])]);
// '[{"0":1},{"0":1},{"0":1}]'
JSON.stringify([
  new Uint8Array([1]),
  new Uint8ClampedArray([1]),
  new Uint16Array([1]),
  new Uint32Array([1]),
]);
// '[{"0":1},{"0":1},{"0":1},{"0":1}]'
JSON.stringify([new Float32Array([1]), new Float64Array([1])]);
// '[{"0":1},{"0":1}]'

// toJSON()
JSON.stringify({
  x: 5,
  y: 6,
  toJSON() {
    return this.x + this.y;
  },
});
// '11'

// Symbols:
JSON.stringify({ x: undefined, y: Object, z: Symbol("") });
// '{}'
JSON.stringify({ [Symbol("foo")]: "foo" });
// '{}'
JSON.stringify({ [Symbol.for("foo")]: "foo" }, [Symbol.for("foo")]);
// '{}'
JSON.stringify({ [Symbol.for("foo")]: "foo" }, (k, v) => {
  if (typeof k === "symbol") {
    return "a symbol";
  }
});
// undefined

// Non-enumerable properties:
JSON.stringify(
  Object.create(null, {
    x: { value: "x", enumerable: false },
    y: { value: "y", enumerable: true },
  }),
);
// '{"y":"y"}'

// BigInt values throw
JSON.stringify({ x: 2n });
// TypeError: BigInt value can't be serialized in JSON
```

### Using a function as replacer

```js
function replacer(key, value) {
  // Filtering out properties
  if (typeof value === "string") {
    return undefined;
  }
  return value;
}

const foo = {
  foundation: "Mozilla",
  model: "box",
  week: 45,
  transport: "car",
  month: 7,
};
JSON.stringify(foo, replacer);
// '{"week":45,"month":7}'
```

If you wish the `replacer` to distinguish an initial object from a key with an empty string property (since both would give the empty string as key and potentially an object as value), you will have to keep track of the iteration count (if it is beyond the first iteration, it is a genuine empty string key).

```js
function makeReplacer() {
  let isInitial = true;

  return (key, value) => {
    if (isInitial) {
      isInitial = false;
      return value;
    }
    if (key === "") {
      // Omit all properties with name "" (except the initial object)
      return undefined;
    }
    return value;
  };
}

const replacer = makeReplacer();
console.log(JSON.stringify({ "": 1, b: 2 }, replacer)); // "{"b":2}"
```

### Using an array as replacer

```js
const foo = {
  foundation: "Mozilla",
  model: "box",
  week: 45,
  transport: "car",
  month: 7,
};

JSON.stringify(foo, ["week", "month"]);
// '{"week":45,"month":7}', only keep "week" and "month" properties
```

### Using the space parameter

Indent the output with one space:

```js
console.log(JSON.stringify({ a: 2 }, null, " "));
/\*
{
 "a": 2
}
\*/
```

Using a tab character mimics standard pretty-print appearance:

```js
console.log(JSON.stringify({ uno: 1, dos: 2 }, null, "\t"));
/\*
{
 "uno": 1,
 "dos": 2
}
\*/
```

### toJSON() behavior

Defining `toJSON()` for an object allows overriding its serialization behavior.

```js
const obj = {
  data: "data",

  toJSON(key) {
    return key ? `Now I am a nested object under key '${key}'` : this;
  },
};

JSON.stringify(obj);
// '{"data":"data"}'

JSON.stringify({ obj });
// '{"obj":"Now I am a nested object under key 'obj'"}'

JSON.stringify([obj]);
// '["Now I am a nested object under key '0'"]'
```

### Issue with serializing circular references

Since the JSON format doesn't support object references (although an IETF draft exists), a `TypeError` will be thrown if one attempts to encode an object with circular references.

```js
const circularReference = {};
circularReference.myself = circularReference;

// Serializing circular references throws "TypeError: cyclic object value"
JSON.stringify(circularReference);
```

To serialize circular references, you can use a library that supports them (e.g. cycle.js by Douglas Crockford) or implement a solution yourself, which will require finding and replacing (or removing) the cyclic references by serializable values.

If you are using `JSON.stringify()` to deep-copy an object, you may instead want to use `structuredClone()`, which supports circular references. JavaScript engine APIs for binary serialization, such as `v8.serialize()`, also support circular references.

### Using JSON.stringify() with localStorage

In a case where you want to store an object created by your user and allow it to be restored even after the browser has been closed, the following example is a model for the applicability of `JSON.stringify()`:

```js
// Creating an example of JSON
const session = {
  screens: [],
  state: true,
};
session.screens.push({ name: "screenA", width: 450, height: 250 });
session.screens.push({ name: "screenB", width: 650, height: 350 });
session.screens.push({ name: "screenC", width: 750, height: 120 });
session.screens.push({ name: "screenD", width: 250, height: 60 });
session.screens.push({ name: "screenE", width: 390, height: 120 });
session.screens.push({ name: "screenF", width: 1240, height: 650 });

// Converting the JSON string with JSON.stringify()
// then saving with localStorage in the name of session
localStorage.setItem("session", JSON.stringify(session));

// Example of how to transform the String generated through
// JSON.stringify() and saved in localStorage in JSON object again
const restoredSession = JSON.parse(localStorage.getItem("session"));

// Now restoredSession variable contains the object that was saved
// in localStorage
console.log(restoredSession);
```

### Well-formed JSON.stringify()

Engines implementing the well-formed JSON.stringify specification will stringify lone surrogates (any code point from U+D800 to U+DFFF) using Unicode escape sequences rather than literally (outputting lone surrogates). Before this change, such strings could not be encoded in valid UTF-8 or UTF-16:

```js
JSON.stringify("\uD800"); // '"�"'
```

But with this change `JSON.stringify()` represents lone surrogates using JSON escape sequences that *can* be encoded in valid UTF-8 or UTF-16:

```js
JSON.stringify("\uD800"); // '"\\ud800"'
```

This change should be backwards-compatible as long as you pass the result of `JSON.stringify()` to APIs such as `JSON.parse()` that will accept any valid JSON text, because they will treat Unicode escapes of lone surrogates as identical to the lone surrogates themselves. *Only* if you are directly interpreting the result of `JSON.stringify()` do you need to carefully handle `JSON.stringify()`'s two possible encodings of these code points.

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-json.stringify |

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

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

See also
--------

* Polyfill of modern `JSON.stringify` behavior (symbol and well-formed unicode) in `core-js`
* `JSON.parse()`


JSON.parse() - JavaScript

JSON.parse()
============

The **`JSON.parse()`** static method parses a JSON string, constructing the JavaScript value or object described by the string. An optional *reviver* function can be provided to perform a transformation on the resulting object before it is returned.

Try it
------

Syntax
------

```js
JSON.parse(text)
JSON.parse(text, reviver)
```

### Parameters

`text`

The string to parse as JSON. See the `JSON` object for a description of JSON syntax.

`reviver` Optional

If a function, this prescribes how each value originally produced by parsing is transformed before being returned. Non-callable values are ignored. The function is called with the following arguments:

`key`

The key associated with the value.

`value`

The value produced by parsing.

### Return value

The `Object`, `Array`, string, number, boolean, or `null` value corresponding to the given JSON `text`.

### Exceptions

`SyntaxError`

Thrown if the string to parse is not valid JSON.

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

`JSON.parse()` parses a JSON string according to the JSON grammar, then evaluates the string as if it's a JavaScript expression. The only instance where a piece of JSON text represents a different value from the same JavaScript expression is when dealing with the `"__proto__"` key — see Object literal syntax vs. JSON.

### The reviver parameter

If a `reviver` is specified, the value computed by parsing is *transformed* before being returned. Specifically, the computed value and all its properties (in a depth-first fashion, beginning with the most nested properties and proceeding to the original value itself) are individually run through the `reviver`.

The `reviver` is called with the object containing the property being processed as `this` (unless you define the `reviver` as an arrow function, in which case there's no separate `this` binding) and two arguments: `key` and `value`, representing the property name as a string (even for arrays) and the property value. If the `reviver` function returns `undefined` (or returns no value — for example, if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value. If the `reviver` only transforms some values and not others, be certain to return all untransformed values as-is — otherwise, they will be deleted from the resulting object.

Similar to the `replacer` parameter of `JSON.stringify()`, for arrays and objects, `reviver` will be last called on the root value with an empty string as the `key` and the root object as the `value`. For other valid JSON values, `reviver` works similarly and is called once with an empty string as the `key` and the value itself as the `value`.

If you return another value from `reviver`, that value will completely replace the originally parsed value. This even applies to the root value. For example:

```js
const transformedObj1 = JSON.parse('[1,5,{"s":1}]', (key, value) => {
  return typeof value === "object" ? undefined : value;
});

console.log(transformedObj1); // undefined
```

There is no way to work around this generically. You cannot specially handle the case where `key` is an empty string, because JSON objects can also contain keys that are empty strings. You need to know very precisely what kind of transformation is needed for each key when implementing the reviver.

Note that `reviver` is run after the value is parsed. So, for example, numbers in JSON text will have already been converted to JavaScript numbers, and may lose precision in the process. To transfer large numbers without loss of precision, serialize them as strings, and revive them to BigInts, or other appropriate arbitrary precision formats.

Examples
--------

### Using JSON.parse()

```js
JSON.parse("{}"); // {}
JSON.parse("true"); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse("null"); // null
```

### Using the reviver parameter

```js
JSON.parse(
  '{"p": 5}',
  (key, value) =>
    typeof value === "number"
      ? value \* 2 // return value \* 2 for numbers
      : value, // return everything else unchanged
);
// { p: 10 }

JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', (key, value) => {
  console.log(key);
  return value;
});
// 1
// 2
// 4
// 6
// 5
// 3
// ""
```

### Using reviver when paired with the replacer of JSON.stringify()

In order for a value to properly round-trip (that is, it gets deserialized to the same original object), the serialization process must preserve the type information. For example, you can use the `replacer` parameter of `JSON.stringify()` for this purpose:

```js
// Maps are normally serialized as objects with no properties.
// We can use the replacer to specify the entries to be serialized.
const map = new Map([
  [1, "one"],
  [2, "two"],
  [3, "three"],
]);

const jsonText = JSON.stringify(map, (key, value) =>
  value instanceof Map ? Array.from(value.entries()) : value,
);

console.log(jsonText);
// [[1,"one"],[2,"two"],[3,"three"]]

const map2 = JSON.parse(jsonText, (key, value) =>
  Array.isArray(value) ? new Map(value) : value,
);

console.log(map2);
// Map { 1 => "one", 2 => "two", 3 => "three" }
```

Because JSON has no syntax space for annotating type metadata, in order to revive values that are not plain objects, you have to consider one of the following:

* Serialize the entire object to a string and prefix it with a type tag.
* "Guess" based on the structure of the data (for example, an array of two-member arrays)
* If the shape of the payload is fixed, based on the property name (for example, all properties called `registry` hold `Map` objects).
### JSON.parse() does not allow trailing commas

```js
// both will throw a SyntaxError
JSON.parse("[1, 2, 3, 4, ]");
JSON.parse('{"foo" : 1, }');
```

### JSON.parse() does not allow single quotes

```js
// will throw a SyntaxError
JSON.parse("{'foo': 1}");
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-json.parse |

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

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

See also
--------

* `JSON.stringify()`


Uint8ClampedArray() constructor - JavaScript

Uint8ClampedArray() constructor
===============================

The **`Uint8ClampedArray()`** constructor creates `Uint8ClampedArray` objects. The contents are initialized to `0`.

Syntax
------

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

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

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

### Parameters

See `TypedArray`.

### Exceptions

See `TypedArray`.

Examples
--------

### Different ways to create a Uint8ClampedArray

```js
// From a length
const uint8c = new Uint8ClampedArray(2);
uint8c[0] = 42;
uint8c[1] = 1337;
console.log(uint8c[0]); // 42
console.log(uint8c[1]); // 255 (clamped)
console.log(uint8c.length); // 2
console.log(uint8c.BYTES\_PER\_ELEMENT); // 1

// From an array
const x = new Uint8ClampedArray([21, 31]);
console.log(x[1]); // 31

// From another TypedArray
const y = new Uint8ClampedArray(x);
console.log(y[0]); // 21

// From an ArrayBuffer
const buffer = new ArrayBuffer(8);
const z = new Uint8ClampedArray(buffer, 1, 4);
console.log(z.byteOffset); // 1

// From an iterable
const iterable = (function\* () {
  yield\* [1, 2, 3];
})();
const uint8cFromIterable = new Uint8ClampedArray(iterable);
console.log(uint8cFromIterable);
// Uint8ClampedArray [1, 2, 3]
```

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

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

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

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

See also
--------

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


Atomics.and() - JavaScript

Atomics.and()
=============

 The **`Atomics.and()`** static
 method computes a bitwise AND with a given value at a given position in the array, and
 returns the old value at that position. This atomic operation guarantees that no other
 write happens until the modified value is written back.

Try it
------

Syntax
------

```js
Atomics.and(typedArray, index, value)
```

### Parameters

`typedArray`

 An integer typed array. One of `Int8Array`, `Uint8Array`,
 `Int16Array`, `Uint16Array`, `Int32Array`,
 `Uint32Array`, `BigInt64Array`, or
 `BigUint64Array`.

`index`

The position in the `typedArray` to compute the bitwise AND.

`value`

The number to compute the bitwise AND with.

### Return value

 The old value at the given position
 (`typedArray[index]`).

### Exceptions

`TypeError`

Thrown if `typedArray` is not one of the allowed integer types.

`RangeError`

Thrown if `index` is out of bounds in the `typedArray`.

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

 The bitwise AND operation only yields 1, if both `a` and `b` are
 1. The truth table for the AND operation is:

| `a` | `b` | `a & b` |
| --- | --- | --- |
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |

 For example, a bitwise AND of `5 & 1` results in `0001` which
 is 1 in decimal.
```

5  0101
1  0001
   ----
1  0001
```

Examples
--------

### Using and()

```js
const sab = new SharedArrayBuffer(1024);
const ta = new Uint8Array(sab);
ta[0] = 5;

Atomics.and(ta, 0, 1); // returns 5, the old value
Atomics.load(ta, 0); // 1
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-atomics.and |

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

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

See also
--------

* `Atomics`
* `Atomics.or()`
* `Atomics.xor()`


Atomics.or() - JavaScript

Atomics.or()
============

 The **`Atomics.or()`** static
 method computes a bitwise OR with a given value at a given position in the array, and
 returns the old value at that position. This atomic operation guarantees that no other
 write happens until the modified value is written back.

Try it
------

Syntax
------

```js
Atomics.or(typedArray, index, value)
```

### Parameters

`typedArray`

 An integer typed array. One of `Int8Array`, `Uint8Array`,
 `Int16Array`, `Uint16Array`, `Int32Array`,
 `Uint32Array`, `BigInt64Array`, or
 `BigUint64Array`.

`index`

The position in the `typedArray` to compute the bitwise OR.

`value`

The number to compute the bitwise OR with.

### Return value

 The old value at the given position
 (`typedArray[index]`).

### Exceptions

`TypeError`

Thrown if `typedArray` is not one of the allowed integer types.

`RangeError`

Thrown if `index` is out of bounds in the `typedArray`.

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

 The bitwise OR operation yields 1, if either `a` or `b` are 1.
 The truth table for the OR operation is:

| `a` | `b` | `a | b` |
| --- | --- | --- |
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 1 |

 For example, a bitwise OR of `5 | 1` results in `0101` which is 5
 in decimal.
```

5  0101
1  0001
   ----
5  0101
```

Examples
--------

### Using or

```js
const sab = new SharedArrayBuffer(1024);
const ta = new Uint8Array(sab);
ta[0] = 2;

Atomics.or(ta, 0, 1); // returns 2, the old value
Atomics.load(ta, 0); // 3
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-atomics.or |

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

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

See also
--------

* `Atomics`
* `Atomics.and()`
* `Atomics.xor()`


Atomics.store() - JavaScript

Atomics.store()
===============

 The **`Atomics.store()`** static
 method stores a given value at the given position in the array and returns that value.

Try it
------

Syntax
------

```js
Atomics.store(typedArray, index, value)
```

### Parameters

`typedArray`

 An integer typed array. One of `Int8Array`, `Uint8Array`,
 `Int16Array`, `Uint16Array`, `Int32Array`,
 `Uint32Array`, `BigInt64Array`, or
 `BigUint64Array`.

`index`

 The position in the `typedArray` to store a
 `value` in.

`value`

The number to store.

### Return value

The value that has been stored.

### Exceptions

`TypeError`

Thrown if `typedArray` is not one of the allowed integer types.

`RangeError`

Thrown if `index` is out of bounds in the `typedArray`.

Examples
--------

### Using store()

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

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-atomics.store |

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

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

See also
--------

* `Atomics`
* `Atomics.load()`


Atomics.sub() - JavaScript

Atomics.sub()
=============

 The **`Atomics.sub()`** static method subtracts a given value
 at a given position in the array and returns the old value at that position. This atomic
 operation guarantees that no other write happens until the modified value is written
 back.

Try it
------

Syntax
------

```js
Atomics.sub(typedArray, index, value)
```

### Parameters

`typedArray`

 An integer typed array. One of `Int8Array`, `Uint8Array`,
 `Int16Array`, `Uint16Array`, `Int32Array`,
 `Uint32Array`, `BigInt64Array`, or
 `BigUint64Array`.

`index`

 The position in the `typedArray` to subtract a
 `value` from.

`value`

The number to subtract.

### Return value

 The old value at the given position
 (`typedArray[index]`).

### Exceptions

`TypeError`

Thrown if `typedArray` is not one of the allowed integer types.

`RangeError`

Thrown if `index` is out of bounds in the `typedArray`.

Examples
--------

### Using sub

```js
const sab = new SharedArrayBuffer(1024);
const ta = new Uint8Array(sab);
ta[0] = 48;

Atomics.sub(ta, 0, 12); // returns 48, the old value
Atomics.load(ta, 0); // 36
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-atomics.sub |

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

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

See also
--------

* `Atomics`
* `Atomics.add()`


Atomics.xor() - JavaScript

Atomics.xor()
=============

 The **`Atomics.xor()`** static
 method computes a bitwise XOR with a given value at a given position in the array, and
 returns the old value at that position. This atomic operation guarantees that no other
 write happens until the modified value is written back.

Try it
------

Syntax
------

```js
Atomics.xor(typedArray, index, value)
```

### Parameters

`typedArray`

 An integer typed array. One of `Int8Array`, `Uint8Array`,
 `Int16Array`, `Uint16Array`, `Int32Array`,
 `Uint32Array`, `BigInt64Array`, or
 `BigUint64Array`.

`index`

The position in the `typedArray` to compute the bitwise XOR.

`value`

The number to compute the bitwise XOR with.

### Return value

The old value at the given position (`typedArray[index]`).

### Exceptions

`TypeError`

Thrown if `typedArray` is not one of the allowed integer types.

`RangeError`

Thrown if `index` is out of bounds in the `typedArray`.

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

 The bitwise XOR operation yields 1, if `a` and `b` are different.
 The truth table for the XOR operation is:

| `a` | `b` | `a ^ b` |
| --- | --- | --- |
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |

 For example, a bitwise XOR of `5 ^ 1` results in `0100` which is
 4 in decimal.
```

5  0101
1  0001
   ----
4  0100
```

Examples
--------

### Using xor

```js
const sab = new SharedArrayBuffer(1024);
const ta = new Uint8Array(sab);
ta[0] = 5;

Atomics.xor(ta, 0, 1); // returns 5, the old value
Atomics.load(ta, 0); // 4
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-atomics.xor |

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

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

See also
--------

* `Atomics`
* `Atomics.and()`
* `Atomics.or()`


Atomics.exchange() - JavaScript

Atomics.exchange()
==================

The **`Atomics.exchange()`** static method exchanges a given value at a given position in the array and returns the old value at that position. This atomic operation guarantees that no other write happens between the read of the old value and the write of the new value.

Try it
------

Syntax
------

```js
Atomics.exchange(typedArray, index, value)
```

### Parameters

`typedArray`

An integer typed array. One of `Int8Array`, `Uint8Array`, `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`, `BigInt64Array`, or `BigUint64Array`.

`index`

The position in the `typedArray` to exchange a `value`.

`value`

The number to exchange.

### Return value

The old value at the given position (`typedArray[index]`).

### Exceptions

`TypeError`

Thrown if `typedArray` is not one of the allowed integer types.

`RangeError`

Thrown if `index` is out of bounds in the `typedArray`.

Examples
--------

### Using exchange()

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

Atomics.exchange(ta, 0, 12); // returns 0, the old value
Atomics.load(ta, 0); // 12
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-atomics.exchange |

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

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

See also
--------

* `Atomics`
* `Atomics.compareExchange()`


Atomics.load() - JavaScript

Atomics.load()
==============

 The **`Atomics.load()`** static
 method returns a value at a given position in the array.

Try it
------

Syntax
------

```js
Atomics.load(typedArray, index)
```

### Parameters

`typedArray`

 An integer typed array. One of `Int8Array`, `Uint8Array`,
 `Int16Array`, `Uint16Array`, `Int32Array`,
 `Uint32Array`, `BigInt64Array`, or
 `BigUint64Array`.

`index`

The position in the `typedArray` to load from.

### Return value

The value at the given position (`typedArray[index]`).

### Exceptions

`TypeError`

Thrown if `typedArray` is not one of the allowed integer types.

`RangeError`

Thrown if `index` is out of bounds in the `typedArray`.

Examples
--------

### Using `load`

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

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-atomics.load |

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

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

See also
--------

* `Atomics`
* `Atomics.store()`


Atomics.waitAsync() - JavaScript

Atomics.waitAsync()
===================

The **`Atomics.waitAsync()`** static method waits asynchronously on a shared memory location and returns a `Promise`.

Unlike `Atomics.wait()`, `waitAsync` is non-blocking and usable on the main thread.

**Note:** This operation only works with an `Int32Array` or `BigInt64Array` that views a `SharedArrayBuffer`.

Syntax
------

```js
Atomics.waitAsync(typedArray, index, value)
Atomics.waitAsync(typedArray, index, value, timeout)
```

### Parameters

`typedArray`

An `Int32Array` or `BigInt64Array` that views a `SharedArrayBuffer`.

`index`

The position in the `typedArray` to wait on.

`value`

The expected value to test.

`timeout` Optional

Time to wait in milliseconds. `NaN` (and values that get converted to `NaN`, such as `undefined`) becomes `Infinity`. Negative values become `0`.

### Return value

An `Object` with the following properties:

`async`

A boolean indicating whether the `value` property is a `Promise` or not.

`value`

If `async` is `false`, it will be a string which is either `"not-equal"` or `"timed-out"` (only when the `timeout` parameter is `0`). If `async` is `true`, it will be a `Promise` which is fulfilled with a string value, either `"ok"` or `"timed-out"`. The promise is never rejected.

### Exceptions

`TypeError`

Thrown if `typedArray` is not an `Int32Array` or `BigInt64Array` that views a `SharedArrayBuffer`.

`RangeError`

Thrown if `index` is out of bounds in the `typedArray`.

Examples
--------

### Using waitAsync()

Given a shared `Int32Array`.

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

 A reading thread is sleeping and waiting on location 0 which is expected to be 0.
 The `result.value` will be a promise.

```js
const result = Atomics.waitAsync(int32, 0, 0, 1000);
// { async: true, value: Promise {<pending>} }
```

In the reading thread or in another thread, the memory location 0 is called and the promise can be resolved with `"ok"`.

```js
Atomics.notify(int32, 0);
// { async: true, value: Promise {<fulfilled>: 'ok'} }
```

If it isn't resolving to `"ok"`, the value in the shared memory location wasn't the expected (the `value` would be `"not-equal"` instead of a promise) or the timeout was reached (the promise will resolve to `"time-out"`).

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-atomics.waitasync |

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

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

See also
--------

* `Atomics`
* `Atomics.wait()`
* `Atomics.notify()`


Atomics.compareExchange() - JavaScript

Atomics.compareExchange()
=========================

The **`Atomics.compareExchange()`** static method exchanges a given replacement value at a given position in the array, if a given expected value equals the old value. It returns the old value at that position whether it was equal to the expected value or not. This atomic operation guarantees that no other write happens until the modified value is written back.

Try it
------

Syntax
------

```js
Atomics.compareExchange(typedArray, index, expectedValue, replacementValue)
```

### Parameters

`typedArray`

An integer typed array. One of `Int8Array`, `Uint8Array`, `Int16Array`, `Uint16Array`, `Int32Array`, `Uint32Array`, `BigInt64Array`, or `BigUint64Array`.

`index`

The position in the `typedArray` to exchange a `replacementValue`.

`expectedValue`

The value to check for equality.

`replacementValue`

The number to exchange.

### Return value

The old value at the given position (`typedArray[index]`).

### Exceptions

`TypeError`

Thrown if `typedArray` is not one of the allowed integer types.

`RangeError`

Thrown if `index` is out of bounds in the `typedArray`.

Examples
--------

### Using compareExchange()

```js
const sab = new SharedArrayBuffer(1024);
const ta = new Uint8Array(sab);
ta[0] = 7;

Atomics.compareExchange(ta, 0, 7, 12); // returns 7, the old value
Atomics.load(ta, 0); // 12
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-atomics.compareexchange |

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

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

See also
--------

* `Atomics`
* `Atomics.exchange()`


Atomics.notify() - JavaScript

Atomics.notify()
================

 The **`Atomics.notify()`** static
 method notifies up some agents that are sleeping in the wait queue.

**Note:** This operation only works with an `Int32Array` or `BigInt64Array` that views a `SharedArrayBuffer`.
 It will return `0` on non-shared `ArrayBuffer` objects.

Syntax
------

```js
Atomics.notify(typedArray, index, count)
```

### Parameters

`typedArray`

An `Int32Array` or `BigInt64Array` that views a `SharedArrayBuffer`.

`index`

The position in the `typedArray` to wake up on.

`count` Optional

The number of sleeping agents to notify. Defaults to `Infinity`.

### Return value

* Returns the number of woken up agents.
* Returns `0`, if a non-shared `ArrayBuffer` object is used.
### Exceptions

`TypeError`

Thrown if `typedArray` is not an `Int32Array` or `BigInt64Array` that views a `SharedArrayBuffer`.

`RangeError`

Thrown if `index` is out of bounds in the `typedArray`.

Examples
--------

### Using `notify`

Given a shared `Int32Array`:

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

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

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

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

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-atomics.notify |

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

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

See also
--------

* `Atomics`
* `Atomics.wait()`
* `Atomics.waitAsync()`


Atomics.isLockFree() - JavaScript

Atomics.isLockFree()
====================

 The **`Atomics.isLockFree()`** static
 method is used to determine whether the `Atomics` methods use locks
 or atomic hardware operations when applied to typed arrays with the given element
 byte size.
 It returns `false` if the given size is not one of the BYTES\_PER\_ELEMENT
 property of integer TypedArray types.

Try it
------

Syntax
------

```js
Atomics.isLockFree(size)
```

### Parameters

`size`

The size in bytes to check.

### Return value

A `true` or `false` value indicating whether the operation is lock free.

Examples
--------

### Using isLockFree

```js
Atomics.isLockFree(1); // true
Atomics.isLockFree(2); // true
Atomics.isLockFree(3); // false
Atomics.isLockFree(4); // true
Atomics.isLockFree(5); // false
Atomics.isLockFree(6); // false
Atomics.isLockFree(7); // false
Atomics.isLockFree(8); // true
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-atomics.islockfree |

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

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

See also
--------

* `Atomics`


Atomics.add() - JavaScript

Atomics.add()
=============

 The **`Atomics.add()`** static
 method adds a given value at a given position in the array and returns the old value at
 that position. This atomic operation guarantees that no other write happens until the
 modified value is written back.

Try it
------

Syntax
------

```js
Atomics.add(typedArray, index, value)
```

### Parameters

`typedArray`

 An integer typed array. One of `Int8Array`, `Uint8Array`,
 `Int16Array`, `Uint16Array`, `Int32Array`,
 `Uint32Array`, `BigInt64Array`, or
 `BigUint64Array`.

`index`

 The position in the `typedArray` to add a
 `value` to.

`value`

The number to add.

### Return value

 The old value at the given position
 (`typedArray[index]`).

### Exceptions

`TypeError`

Thrown if `typedArray` is not one of the allowed integer types.

`RangeError`

Thrown if `index` is out of bounds in the `typedArray`.

Examples
--------

### Using add()

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

Atomics.add(ta, 0, 12); // returns 0, the old value
Atomics.load(ta, 0); // 12
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-atomics.add |

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

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

See also
--------

* `Atomics`
* `Atomics.sub()`


Atomics.wait() - JavaScript

Atomics.wait()
==============

 The **`Atomics.wait()`** static
 method verifies that a shared memory location still contains a
 given value and if so sleeps, awaiting a wake-up notification or times out. It returns a string which
 is either `"ok"`, `"not-equal"`, or `"timed-out"`.

**Note:** This operation only works with an `Int32Array` or `BigInt64Array` that views a `SharedArrayBuffer`, and may not be allowed on the main thread.
 For a non-blocking, asynchronous version of this method, see `Atomics.waitAsync()`.

Syntax
------

```js
Atomics.wait(typedArray, index, value)
Atomics.wait(typedArray, index, value, timeout)
```

### Parameters

`typedArray`

An `Int32Array` or `BigInt64Array` that views a `SharedArrayBuffer`.

`index`

The position in the `typedArray` to wait on.

`value`

The expected value to test.

`timeout` Optional

Time to wait in milliseconds. `NaN` (and values that get converted to `NaN`, such as `undefined`) becomes `Infinity`. Negative values become `0`.

### Return value

A string which is either `"ok"`, `"not-equal"`, or `"timed-out"`.

### Exceptions

`TypeError`

Thrown in one of the following cases:

* If `typedArray` is not an `Int32Array` or `BigInt64Array` that views a `SharedArrayBuffer`.
* If the current thread cannot be blocked (for example, because it's the main thread).

`RangeError`

Thrown if `index` is out of bounds in the `typedArray`.

Examples
--------

### Using wait()

Given a shared `Int32Array`:

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

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

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

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

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-atomics.wait |

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

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

See also
--------

* `Atomics`
* `Atomics.waitAsync()`
* `Atomics.notify()`


WeakMap.prototype.has() - JavaScript

WeakMap.prototype.has()
=======================

 The **`has()`** method of `WeakMap` instances returns a boolean indicating whether an
 element with the specified key exists in this `WeakMap` or not.

Try it
------

Syntax
------

```js
has(key)
```

### Parameters

`key`

The key of the element to test for presence in the `WeakMap` object.

### Return value

Returns `true` if an element with the specified key exists in the `WeakMap` object; otherwise `false`. Always returns `false` if `key` is not an object or a non-registered symbol.

Examples
--------

### Using the has method

```js
const wm = new WeakMap();
wm.set(window, "foo");

wm.has(window); // returns true
wm.has("baz"); // returns false
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-weakmap.prototype.has |

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

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

See also
--------

* `WeakMap`
* `WeakMap.prototype.set()`
* `WeakMap.prototype.get()`


WeakMap() constructor - JavaScript

WeakMap() constructor
=====================

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

Syntax
------

```js
new WeakMap()
new WeakMap(iterable)
```

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

### Parameters

`iterable`

An `Array` or other iterable object that implements an @@iterator method that returns an iterator object that produces a two-element array-like object whose first element is a value that will be used as a `WeakMap` key and whose second element is the value to associate with that key. Each key-value pair will be added to the new `WeakMap`. null is treated as undefined.

Examples
--------

### Using WeakMap

```js
const wm1 = new WeakMap();
const wm2 = new WeakMap();
const wm3 = new WeakMap();
const o1 = {};
const o2 = function () {};
const o3 = window;

wm1.set(o1, 37);
wm1.set(o2, "azerty");
wm2.set(o1, o2); // a value can be anything, including an object or a function
wm2.set(o3, undefined);
wm2.set(wm1, wm2); // keys and values can be any objects. Even WeakMaps!

wm1.get(o2); // "azerty"
wm2.get(o2); // undefined, because there is no key for o2 on wm2
wm2.get(o3); // undefined, because that is the set value

wm1.has(o2); // true
wm2.has(o2); // false
wm2.has(o3); // true (even if the value itself is 'undefined')

wm3.set(o1, 37);
wm3.get(o1); // 37

wm1.has(o1); // true
wm1.delete(o1);
wm1.has(o1); // false
```

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

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

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

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

See also
--------

* Polyfill of `WeakMap` in `core-js`
* `WeakMap` in the JavaScript guide
* Hiding Implementation Details with ECMAScript 6 WeakMaps
* `Map`
* `Set`
* `WeakSet`


WeakMap.prototype.get() - JavaScript

WeakMap.prototype.get()
=======================

The **`get()`** method of `WeakMap` instances returns a specified element from this `WeakMap`.

Try it
------

Syntax
------

```js
get(key)
```

### Parameters

`key`

The key of the element to return from the `WeakMap` object.

### Return value

 The element associated with the specified key in the `WeakMap` object. If
 the key can't be found, `undefined` is returned. Always returns
 `undefined` if `key` is not an object or a non-registered symbol.

Examples
--------

### Using the get() method

```js
const wm = new WeakMap();
wm.set(window, "foo");

wm.get(window); // Returns "foo".
wm.get("baz"); // Returns undefined.
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-weakmap.prototype.get |

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

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

See also
--------

* `WeakMap`
* `WeakMap.prototype.set()`
* `WeakMap.prototype.has()`


WeakMap.prototype.delete() - JavaScript

WeakMap.prototype.delete()
==========================

The **`delete()`** method of `WeakMap` instances removes the specified element from this `WeakMap`.

Try it
------

Syntax
------

```js
weakMapInstance.delete(key)
```

### Parameters

`key`

The key of the element to remove from the `WeakMap` object.

### Return value

`true` if an element in the `WeakMap` object has been removed successfully. `false` if the key is not found in the `WeakMap`. Always returns `false` if `key` is not an object or a non-registered symbol.

Examples
--------

### Using the delete() method

```js
const wm = new WeakMap();
wm.set(window, "foo");

wm.delete(window); // Returns true. Successfully removed.

wm.has(window); // Returns false. The window object is no longer in the WeakMap.
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-weakmap.prototype.delete |

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

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

See also
--------

* `WeakMap`


WeakMap.prototype.set() - JavaScript

WeakMap.prototype.set()
=======================

 The **`set()`** method of `WeakMap` instances adds a new element with a specified key
 and value to this `WeakMap`.

Try it
------

Syntax
------

```js
set(key, value)
```

### Parameters

`key`

Must be either an object or a non-registered symbol. The key of the entry to add to the `WeakMap` object.

`value`

Any value representing the value of the entry to add to the `WeakMap` object.

### Return value

The `WeakMap` object.

### Exceptions

`TypeError`

Thrown if `key` is not an object or a non-registered symbol.

Examples
--------

### Using the set() method

```js
const wm = new WeakMap();
const obj = {};

// Add new elements to the WeakMap
wm.set(obj, "foo").set(window, "bar"); // chainable

// Update an element in the WeakMap
wm.set(obj, "baz");

// Using a non-registered symbol as key
const sym = Symbol("foo");
wm.set(sym, "baz");
wm.set(Symbol.iterator, "qux");
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-weakmap.prototype.set |

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

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

See also
--------

* `WeakMap`
* `WeakMap.prototype.get()`
* `WeakMap.prototype.has()`


SharedArrayBuffer.prototype.growable - JavaScript

SharedArrayBuffer.prototype.growable
====================================

The **`growable`** accessor property of `SharedArrayBuffer` instances returns whether this `SharedArrayBuffer` can be grow or not.

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

The `growable` 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 array is constructed. If a `maxByteLength` option was set in the constructor, `growable` will return `true`; if not, it will return `false`.

Examples
--------

### Using growable

In this example, we create a 8-byte buffer that is growable to a max length of 16 bytes, then check its `growable` property, growing it if `growable` returns `true`:

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

if (buffer.growable) {
  console.log("SAB is growable!");
  buffer.grow(12);
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-sharedarraybuffer.prototype.growable |

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

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

See also
--------

* `SharedArrayBuffer`
* `SharedArrayBuffer.prototype.grow()`
* `SharedArrayBuffer.prototype.maxByteLength`


SharedArrayBuffer[@@species] - JavaScript

SharedArrayBuffer[@@species]
============================

The **`SharedArrayBuffer[@@species]`** static accessor property returns the constructor used to construct return values from `SharedArrayBuffer` methods.

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

Syntax
------

```js
SharedArrayBuffer[Symbol.species]
```

### Return value

The value of the constructor (`this`) on which `get @@species` was called. The return value is used to construct return values from array buffer methods that create new array buffer.

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

The `@@species` accessor property returns the default constructor for `SharedArrayBuffer` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically:

```js
// Hypothetical underlying implementation for illustration
class SharedArrayBuffer {
  static get [Symbol.species]() {
    return this;
  }
}
```

Because of this polymorphic implementation, `@@species` of derived subclasses would also return the constructor itself by default.

```js
class SubArrayBuffer extends SharedArrayBuffer {}
SubArrayBuffer[Symbol.species] === SharedArrayBuffer; // true
```

When calling array buffer methods that do not mutate the existing array but return a new array buffer instance (for example, `slice()`), the array's `constructor[@@species]` will be accessed. The returned constructor will be used to construct the return value of the array buffer method.

Examples
--------

### Species in ordinary objects

The `@@species` property returns the default constructor function, which is the `SharedArrayBuffer` constructor for `SharedArrayBuffer`.

```js
SharedArrayBuffer[Symbol.species]; // function SharedArrayBuffer()
```

### Species in derived objects

In an instance of a custom `SharedArrayBuffer` subclass, such as `MySharedArrayBuffer`, the `MySharedArrayBuffer` species is the `MySharedArrayBuffer` constructor. However, you might want to overwrite this, in order to return parent `SharedArrayBuffer` objects in your derived class methods:

```js
class MySharedArrayBuffer extends SharedArrayBuffer {
  // Overwrite MySharedArrayBuffer species to the parent SharedArrayBuffer constructor
  static get [Symbol.species]() {
    return SharedArrayBuffer;
  }
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-sharedarraybuffer-@@species |

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

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

See also
--------

* `SharedArrayBuffer`
* `Symbol.species`


SharedArrayBuffer() constructor - JavaScript

SharedArrayBuffer() constructor
===============================

**Note:** The `SharedArrayBuffer` constructor may not always be globally available unless certain security requirements are met.

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

Try it
------

Syntax
------

```js
new SharedArrayBuffer(length)
new SharedArrayBuffer(length, options)
```

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

### Parameters

`length`

The size, in bytes, of the array buffer to create.

`options` Optional

An object, which can contain the following properties:

`maxByteLength` Optional

The maximum size, in bytes, that the shared array buffer can be resized to.

### Return value

 A new `SharedArrayBuffer` object of the specified size, with its `maxByteLength` property set to the specified `maxByteLength` if one was specified. Its contents are
 initialized to 0.

Examples
--------

### Always use the new operator to create a SharedArrayBuffer

`SharedArrayBuffer` constructors are required to be constructed with a
 `new` operator. Calling a `SharedArrayBuffer`
 constructor as a function without `new` will throw a `TypeError`.

```js
const sab = SharedArrayBuffer(1024);
// TypeError: calling a builtin SharedArrayBuffer constructor
// without new is forbidden
```

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

### Growing a growable SharedArrayBuffer

In this example, we create an 8-byte buffer that is growable to a max length of 16 bytes, then `grow()` it to 12 bytes:

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

buffer.grow(12);
```

**Note:** It is recommended that `maxByteLength` is set to the smallest value possible for your use case. It should never exceed `1073741824` (1GB), to reduce the risk of out-of-memory errors.

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

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

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

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

See also
--------

* `Atomics`
* `ArrayBuffer`
* JavaScript typed arrays guide


SharedArrayBuffer.prototype.maxByteLength - JavaScript

SharedArrayBuffer.prototype.maxByteLength
=========================================

The **`maxByteLength`** accessor property of `SharedArrayBuffer` instances returns the maximum length (in bytes) that this `SharedArrayBuffer` can be grown to.

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

The `maxByteLength` 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 shared array is constructed, set via the `maxByteLength` option of the `SharedArrayBuffer()` constructor, and cannot be changed.

If this `SharedArrayBuffer` was constructed without specifying a `maxByteLength` value, this property returns a value equal to the value of the `SharedArrayBuffer`'s `byteLength`.

Examples
--------

### Using maxByteLength

In this example, we create a 8-byte buffer that is resizable to a max length of 16 bytes, then return its `maxByteLength`:

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

buffer.maxByteLength; // 16
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-sharedarraybuffer.prototype.maxbytelength |

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

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

See also
--------

* `SharedArrayBuffer`


SharedArrayBuffer.prototype.grow() - JavaScript

SharedArrayBuffer.prototype.grow()
==================================

The **`grow()`** method of `SharedArrayBuffer` instances grows the `SharedArrayBuffer` to the specified size, in bytes.

Syntax
------

```js
grow(newLength)
```

### Parameters

`newLength`

The new length, in bytes, to resize the `SharedArrayBuffer` to.

### Return value

None (`undefined`).

### Exceptions

`TypeError`

Thrown if the `SharedArrayBuffer` is not growable.

`RangeError`

Thrown if `newLength` is larger than the `maxByteLength` of the `SharedArrayBuffer` or smaller than the `byteLength`.

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

The `grow()` method grows a `SharedArrayBuffer` to the size specified by the `newLength` parameter, provided that the `SharedArrayBuffer` is growable and the new size is less than or equal to the `maxByteLength` of the `SharedArrayBuffer`. New bytes are initialized to 0.

Examples
--------

### Using grow()

In this example, we create a 8-byte buffer that is growable to a max length of 16 bytes, then check its `growable` property, growing it if `growable` returns `true`:

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

if (buffer.growable) {
  console.log("SAB is growable!");
  buffer.grow(12);
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-sharedarraybuffer.prototype.grow |

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

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

See also
--------

* `SharedArrayBuffer`
* `SharedArrayBuffer.prototype.growable`
* `SharedArrayBuffer.prototype.maxByteLength`


SharedArrayBuffer.prototype.slice() - JavaScript

SharedArrayBuffer.prototype.slice()
===================================

The **`slice()`** method of `SharedArrayBuffer` instances returns a new `SharedArrayBuffer` whose contents are a copy of this `SharedArrayBuffer`'s bytes from `start`, inclusive, up to `end`, exclusive. If either `start` or `end` is negative, it refers to an index from the end of the array, as opposed to from the beginning.

Try it
------

Syntax
------

```js
slice()
slice(start)
slice(start, end)
```

### Parameters

`start` Optional

Zero-based index at which to start extraction, converted to an integer.

* Negative index counts back from the end of the buffer — if `start < 0`, `start + buffer.length` is used.
* If `start < -buffer.length` or `start` is omitted, `0` is used.
* If `start >= buffer.length`, nothing is extracted.

`end` Optional

Zero-based index at which to end extraction, converted to an integer. `slice()` extracts up to but not including `end`.

* Negative index counts back from the end of the buffer — if `end < 0`, `end + buffer.length` is used.
* If `end < -buffer.length`, `0` is used.
* If `end >= buffer.length` or `end` is omitted, `buffer.length` is used, causing all elements until the end to be extracted.
* If `end` is positioned before or at `start` after normalization, nothing is extracted.

### Return value

A new `SharedArrayBuffer` containing the extracted elements.

Examples
--------

### Using slice()

```js
const sab = new SharedArrayBuffer(1024);
sab.slice(); // SharedArrayBuffer { byteLength: 1024 }
sab.slice(2); // SharedArrayBuffer { byteLength: 1022 }
sab.slice(-2); // SharedArrayBuffer { byteLength: 2 }
sab.slice(0, 1); // SharedArrayBuffer { byteLength: 1 }
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-sharedarraybuffer.prototype.slice |

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

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

See also
--------

* `SharedArrayBuffer`
* `ArrayBuffer.prototype.slice()`


SharedArrayBuffer.prototype.byteLength - JavaScript

SharedArrayBuffer.prototype.byteLength
======================================

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

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 the shared array is constructed and cannot be changed.

Examples
--------

### Using byteLength

```js
const sab = new SharedArrayBuffer(1024);
sab.byteLength; // 1024
```

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

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

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

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

See also
--------

* `SharedArrayBuffer`


InternalError() constructor - JavaScript

InternalError() constructor
===========================

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

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

Syntax
------

```js
new InternalError()
new InternalError(message)
new InternalError(message, options)
new InternalError(message, fileName)
new InternalError(message, fileName, lineNumber)

InternalError()
InternalError(message)
InternalError(message, options)
InternalError(message, fileName)
InternalError(message, fileName, lineNumber)
```

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

### Parameters

`message` Optional

Human-readable description of the 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.

`fileName` Optional
Non-standard

The name of the file containing the code that caused the exception

`lineNumber` Optional
Non-standard

The line number of the code that caused the exception

Examples
--------

### Creating a new InternalError

```js
new InternalError("Engine failure");
```

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

Not part of any standard.

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

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

See also
--------

* `Error`


AsyncFunction() constructor - JavaScript

AsyncFunction() constructor
===========================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`AsyncFunction()`** constructor creates `AsyncFunction` objects.

Note that `AsyncFunction` is *not* a global object. It can be obtained with the following code:

```js
const AsyncFunction = async function () {}.constructor;
```

The `AsyncFunction()` constructor is not intended to be used directly, and all caveats mentioned in the `Function()` description apply to `AsyncFunction()`.

Syntax
------

```js
new AsyncFunction(functionBody)
new AsyncFunction(arg1, functionBody)
new AsyncFunction(arg1, arg2, functionBody)
new AsyncFunction(arg1, arg2, /\* …, \*/ argN, functionBody)

AsyncFunction(functionBody)
AsyncFunction(arg1, functionBody)
AsyncFunction(arg1, arg2, functionBody)
AsyncFunction(arg1, arg2, /\* …, \*/ argN, functionBody)
```

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

### Parameters

See `Function()`.

Examples
--------

### Creating an async function from an AsyncFunction() constructor

```js
function resolveAfter2Seconds(x) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}

const AsyncFunction = async function () {}.constructor;

const fn = new AsyncFunction(
  "a",
  "b",
  "return await resolveAfter2Seconds(a) + await resolveAfter2Seconds(b);",
);

fn(10, 20).then((v) => {
  console.log(v); // prints 30 after 4 seconds
});
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-async-function-constructor |

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

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

See also
--------

* `async function`
* `async function` expression
* `Function()` constructor


Number() constructor - JavaScript

Number() constructor
====================

The **`Number()`** constructor creates `Number` objects. When called as a function, it returns primitive values of type Number.

Syntax
------

```js
new Number(value)
Number(value)
```

**Note:** `Number()` can be called with or without `new`, but with different effects. See Return value.

### Parameters

`value`

The numeric value of the object being created.

### Return value

When `Number` is called as a constructor (with `new`), it creates a `Number` object, which is **not** a primitive.

When `Number` is called as a function, it coerces the parameter to a number primitive. BigInts are converted to numbers. If the value can't be converted, it returns `NaN`.

**Warning:** You should rarely find yourself using `Number` as a constructor.

Examples
--------

### Creating Number objects

```js
const a = new Number("123"); // a === 123 is false
const b = Number("123"); // b === 123 is true
a instanceof Number; // is true
b instanceof Number; // is false
typeof a; // "object"
typeof b; // "number"
```

### Using Number() to convert a BigInt to a number

`Number()` is the only case where a BigInt can be converted to a number without throwing, because it's very explicit.

```js
+1n; // TypeError: Cannot convert a BigInt value to a number
0 + 1n; // TypeError: Cannot mix BigInt and other types, use explicit conversions
```

```js
Number(1n); // 1
```

Note that this may result in loss of precision, if the BigInt is too large to be safely represented.

```js
BigInt(Number(2n \*\* 54n + 1n)) === 2n \*\* 54n + 1n; // false
```

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

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

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

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

See also
--------

* Polyfill of modern `Number` behavior (with support binary and octal literals) in `core-js`
* `NaN`
* `Math`
* `BigInt`


Number.prototype.toExponential() - JavaScript

Number.prototype.toExponential()
================================

 The **`toExponential()`** method of `Number` values returns a string representing
 this number in exponential notation.

Try it
------

Syntax
------

```js
toExponential()
toExponential(fractionDigits)
```

### Parameters

`fractionDigits` Optional

 Optional. An integer specifying the number of digits after the decimal point.
 Defaults to as many digits as necessary to specify the number.

### Return value

 A string representing the given `Number` object in exponential notation
 with one digit before the decimal point, rounded to
 `fractionDigits` digits after the decimal point.

### Exceptions

`RangeError`

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

`TypeError`

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

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

 If the `fractionDigits` argument is omitted, the number of digits
 after the decimal point defaults to the number of digits necessary to represent the
 value uniquely.

 If you use the `toExponential()` method for a numeric literal and the
 numeric literal has no exponent and no decimal point, leave whitespace(s) before the dot
 that precedes the method call to prevent the dot from being interpreted as a decimal
 point.

 If a number has more digits than requested by the
 `fractionDigits` parameter, the number is rounded to the nearest
 number represented by `fractionDigits` digits. See the discussion
 of rounding in the description of the `toFixed()` method, which also applies to `toExponential()`.

Examples
--------

### Using toExponential

```js
const numObj = 77.1234;

console.log(numObj.toExponential()); // 7.71234e+1
console.log(numObj.toExponential(4)); // 7.7123e+1
console.log(numObj.toExponential(2)); // 7.71e+1
console.log((77.1234).toExponential()); // 7.71234e+1
console.log((77).toExponential()); // 7.7e+1
```

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

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

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

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

See also
--------

* Polyfill of `Number.prototype.toExponential` with many bug fixes in `core-js`
* `Number.prototype.toFixed()`
* `Number.prototype.toPrecision()`
* `Number.prototype.toString()`


Number.MIN_SAFE_INTEGER - JavaScript

Number.MIN\_SAFE\_INTEGER
=========================

The **`Number.MIN_SAFE_INTEGER`** static data property represents the minimum safe integer in JavaScript, or -(253 - 1).

To represent integers smaller than this, consider using `BigInt`.

Try it
------

Value
-----

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

| Property attributes of `Number.MIN_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 correctly compare them. For example, `Number.MIN_SAFE_INTEGER - 1 === Number.MIN_SAFE_INTEGER - 2` will evaluate to true, which is mathematically incorrect. See `Number.isSafeInteger()` for more information.

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

Examples
--------

### Using MIN\_SAFE\_INTEGER

```js
Number.MIN\_SAFE\_INTEGER; // -9007199254740991
-(2 \*\* 53 - 1); // -9007199254740991
```

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

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

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

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

See also
--------

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


Number.MIN_VALUE - JavaScript

Number.MIN\_VALUE
=================

The **`Number.MIN_VALUE`** static data property represents the smallest positive numeric value representable in JavaScript.

Try it
------

Value
-----

2-1074, or `5E-324`.

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

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

`Number.MIN_VALUE` is the smallest positive number (not the most negative number) that can be represented within float precision — in other words, the number closest to 0. The ECMAScript spec doesn't define a precise value that implementations are required to support — instead the spec says, *"must be the smallest non-zero positive value that can actually be represented by the implementation"*. This is because small IEEE-754 floating point numbers are denormalized, but implementations are not required to support this representation, in which case `Number.MIN_VALUE` may be larger.

In practice, its precise value in mainstream engines like V8 (used by Chrome, Edge, Node.js), SpiderMonkey (used by Firefox), and JavaScriptCore (used by Safari) is 2-1074, or `5E-324`.

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

Examples
--------

### Using MIN\_VALUE

The following code divides two numeric values. If the result is greater than or equal to `MIN_VALUE`, the `func1` function is called; otherwise, the `func2` function is called.

```js
if (num1 / num2 >= Number.MIN\_VALUE) {
  func1();
} else {
  func2();
}
```

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

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

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

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

See also
--------

* `Number.MAX_VALUE`


Number.POSITIVE_INFINITY - JavaScript

Number.POSITIVE\_INFINITY
=========================

The **`Number.POSITIVE_INFINITY`** static data property represents the positive Infinity value.

Try it
------

Value
-----

The same as the value of the global `Infinity` property.

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

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

The `Number.POSITIVE_INFINITY` value behaves slightly differently than mathematical infinity:

* Any positive value, including `POSITIVE_INFINITY`, multiplied by `POSITIVE_INFINITY` is `POSITIVE_INFINITY`.
* Any negative value, including `NEGATIVE_INFINITY`, multiplied by `POSITIVE_INFINITY` is `NEGATIVE_INFINITY`.
* Any positive number divided by `POSITIVE_INFINITY` is positive zero (as defined in IEEE 754).
* Any negative number divided by `POSITIVE_INFINITY` is negative zero (as defined in IEEE 754.
* Zero multiplied by `POSITIVE_INFINITY` is `NaN`.
* `NaN` multiplied by `POSITIVE_INFINITY` is `NaN`.
* `POSITIVE_INFINITY`, divided by any negative value except `NEGATIVE_INFINITY`, is `NEGATIVE_INFINITY`.
* `POSITIVE_INFINITY`, divided by any positive value except `POSITIVE_INFINITY`, is `POSITIVE_INFINITY`.
* `POSITIVE_INFINITY`, divided by either `NEGATIVE_INFINITY` or `POSITIVE_INFINITY`, is `NaN`.
* `Number.POSITIVE_INFINITY > x` is true for any number *x* that isn't `POSITIVE_INFINITY`.

You might use the `Number.POSITIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that `NaN` would be more appropriate in such a case.

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

Examples
--------

### Using POSITIVE\_INFINITY

In the following example, the variable `bigNumber` is assigned a value that is larger than the maximum value. When the `if` statement executes, `bigNumber` has the value `Infinity`, so `bigNumber` is set to a more manageable value before continuing.

```js
let bigNumber = Number.MAX\_VALUE \* 2;

if (bigNumber === Number.POSITIVE\_INFINITY) {
  bigNumber = returnFinite();
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-number.positive\_infinity |

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

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

See also
--------

* `Number.NEGATIVE_INFINITY`
* `Number.isFinite()`
* `Infinity`
* `isFinite()`


Number.parseFloat() - JavaScript

Number.parseFloat()
===================

The **`Number.parseFloat()`** static method parses an argument and returns a floating point number. If a number cannot be parsed from the argument, it returns `NaN`.

Try it
------

Syntax
------

```js
Number.parseFloat(string)
```

### Parameters

`string`

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

### Return value

A floating point number parsed from the given `string`.

Or `NaN` when the first non-whitespace character cannot be converted to a number.

Examples
--------

### Number.parseFloat vs. parseFloat

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

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

Its purpose is modularization of globals.

See `parseFloat()` for more detail and examples.

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

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

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

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

See also
--------

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


Number.isNaN() - JavaScript

Number.isNaN()
==============

The **`Number.isNaN()`** static method determines whether the passed value is the number value `NaN`, and returns `false` if the input is not of the Number type. It is a more robust version of the original, global `isNaN()` function.

Try it
------

Syntax
------

```js
Number.isNaN(value)
```

### Parameters

`value`

The value to be tested for `NaN`.

### Return value

The boolean value `true` if the given value is a number with value `NaN`. Otherwise, `false`.

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

The function `Number.isNaN()` provides a convenient way to check for equality with `NaN`. Note that you cannot test for equality with `NaN` using either the `==` or `===` operators, because unlike all other value comparisons in JavaScript, these evaluate to `false` whenever one operand is `NaN`, even if the other operand is also `NaN`.

Since `x !== x` is only true for `NaN` among all possible JavaScript values, `Number.isNaN(x)` can also be replaced with a test for `x !== x`, despite the latter being less readable.

As opposed to the global `isNaN()` function, the `Number.isNaN()` method doesn't force-convert the parameter to a number. This makes it safe to pass values that would normally convert to `NaN` but aren't actually the same value as `NaN`. This also means that only values of the Number type that are also `NaN` return `true`.

Examples
--------

### Using isNaN()

```js
Number.isNaN(NaN); // true
Number.isNaN(Number.NaN); // true
Number.isNaN(0 / 0); // true
Number.isNaN(37); // false
```

### Difference between Number.isNaN() and global isNaN()

`Number.isNaN()` doesn't attempt to convert the parameter to a number, so non-numbers always return `false`. The following are all `false`:

```js
Number.isNaN("NaN");
Number.isNaN(undefined);
Number.isNaN({});
Number.isNaN("blabla");
Number.isNaN(true);
Number.isNaN(null);
Number.isNaN("37");
Number.isNaN("37.37");
Number.isNaN("");
Number.isNaN(" ");
```

The global `isNaN()` coerces its parameter to a number:

```js
isNaN("NaN"); // true
isNaN(undefined); // true
isNaN({}); // true
isNaN("blabla"); // true
isNaN(true); // false, this is coerced to 1
isNaN(null); // false, this is coerced to 0
isNaN("37"); // false, this is coerced to 37
isNaN("37.37"); // false, this is coerced to 37.37
isNaN(""); // false, this is coerced to 0
isNaN(" "); // false, this is coerced to 0
```

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

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

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

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

See also
--------

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


Number.isFinite() - JavaScript

Number.isFinite()
=================

The **`Number.isFinite()`** static method determines whether the passed value is a finite number — that is, it checks that a given value is a number, and the number is neither positive `Infinity`, negative `Infinity`, nor `NaN`.

Try it
------

Syntax
------

```js
Number.isFinite(value)
```

### Parameters

`value`

The value to be tested for finiteness.

### Return value

The boolean value `true` if the given value is a finite number. Otherwise `false`.

Examples
--------

### Using isFinite()

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

Number.isFinite(0); // true
Number.isFinite(2e64); // true
```

### Difference between Number.isFinite() and global isFinite()

In comparison to the global `isFinite()` function, this method doesn't first convert the parameter to a number. This means only values of the type number *and* are finite return `true`, and non-numbers always return `false`.

```js
isFinite("0"); // true; coerced to number 0
Number.isFinite("0"); // false
isFinite(null); // true; coerced to number 0
Number.isFinite(null); // false
```

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

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

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

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

See also
--------

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


Number.prototype.toLocaleString() - JavaScript

Number.prototype.toLocaleString()
=================================

The **`toLocaleString()`** method of `Number` values returns a string with a language-sensitive representation of this number. In implementations with `Intl.NumberFormat` API support, this method simply calls `Intl.NumberFormat`.

Every time `toLocaleString` is called, it has to perform a search in a big database of localization strings, which is potentially inefficient. When the method is called many times with the same arguments, it is better to create a `Intl.NumberFormat` object and use its `format()` method, because a `NumberFormat` object remembers the arguments passed to it and may decide to cache a slice of the database, so future `format` calls can search for localization strings within a more constrained context.

Try it
------

Syntax
------

```js
toLocaleString()
toLocaleString(locales)
toLocaleString(locales, options)
```

### Parameters

The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used.

In implementations that support the `Intl.NumberFormat` API, these parameters correspond exactly to the `Intl.NumberFormat()` constructor's parameters. Implementations without `Intl.NumberFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent.

`locales` Optional

A string with a BCP 47 language tag, or an array of such strings. Corresponds to the `locales` parameter of the `Intl.NumberFormat()` constructor.

In implementations without `Intl.NumberFormat` support, this parameter is ignored and the host's locale is usually used.

`options` Optional

An object adjusting the output format. Corresponds to the `options` parameter of the `Intl.NumberFormat()` constructor.

In implementations without `Intl.NumberFormat` support, this parameter is ignored.

See the `Intl.NumberFormat()` constructor for details on these parameters and how to use them.

### Return value

A string representing the given number according to language-specific conventions.

In implementations with `Intl.NumberFormat`, this is equivalent to `new Intl.NumberFormat(locales, options).format(number)`.

**Note:** Most of the time, the formatting returned by `toLocaleString()` is consistent. However, the output may vary with time, language, and implementation — output variations are by design and allowed by the specification. You should not compare the results of `toLocaleString()` to static values.

Examples
--------

### Using toLocaleString()

Basic use of this method without specifying a `locale` returns a formatted string in the default locale and with default options.

```js
const number = 3500;

console.log(number.toLocaleString()); // "3,500" if in U.S. English locale
```

### Checking for support for locales and options parameters

The `locales` and `options` parameters may not be supported in all implementations, because support for the internationalization API is optional, and some systems may not have the necessary data. For implementations without internationalization support, `toLocaleString()` always uses the system's locale, which may not be what you want. Because any implementation that supports the `locales` and `options` parameters must support the `Intl` API, you can check the existence of the latter for support:

```js
function toLocaleStringSupportsLocales() {
  return (
    typeof Intl === "object" &&
    !!Intl &&
    typeof Intl.NumberFormat === "function"
  );
}
```

### Using locales

 This example shows some of the variations in localized number formats. In order to get
 the format of the language used in the user interface of your application, make sure to
 specify that language (and possibly some fallback languages) using the
 `locales` argument:

```js
const number = 123456.789;

// German uses comma as decimal separator and period for thousands
console.log(number.toLocaleString("de-DE"));
// 123.456,789

// Arabic in most Arabic speaking countries uses Eastern Arabic digits
console.log(number.toLocaleString("ar-EG"));
// ١٢٣٤٥٦٫٧٨٩

// India uses thousands/lakh/crore separators
console.log(number.toLocaleString("en-IN"));
// 1,23,456.789

// the nu extension key requests a numbering system, e.g. Chinese decimal
console.log(number.toLocaleString("zh-Hans-CN-u-nu-hanidec"));
// 一二三,四五六.七八九

// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
console.log(number.toLocaleString(["ban", "id"]));
// 123.456,789
```

### Using options

The results provided by `toLocaleString()` can be customized using the `options` parameter:

```js
const number = 123456.789;

// request a currency format
console.log(
  number.toLocaleString("de-DE", { style: "currency", currency: "EUR" }),
);
// 123.456,79 €

// the Japanese yen doesn't use a minor unit
console.log(
  number.toLocaleString("ja-JP", { style: "currency", currency: "JPY" }),
);
// ￥123,457

// limit to three significant digits
console.log(number.toLocaleString("en-IN", { maximumSignificantDigits: 3 }));
// 1,23,000

// Use the host default language with options for number formatting
const num = 30000.65;
console.log(
  num.toLocaleString(undefined, {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  }),
);
// "30,000.65" where English is the default language, or
// "30.000,65" where German is the default language, or
// "30 000,65" where French is the default language
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-number.prototype.tolocalestring |
| ECMAScript Internationalization API Specification # sup-number.prototype.tolocalestring |

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

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

See also
--------

* `Intl.NumberFormat`
* `Number.prototype.toString()`


Number.prototype.toPrecision() - JavaScript

Number.prototype.toPrecision()
==============================

 The **`toPrecision()`** method of `Number` values returns a string representing
 this number to the specified precision.

Try it
------

Syntax
------

```js
toPrecision()
toPrecision(precision)
```

### Parameters

`precision` Optional

An integer specifying the number of significant digits.

### Return value

 A string representing a `Number` object in fixed-point or exponential
 notation rounded to `precision` significant digits. See the discussion of
 rounding in the description of the `Number.prototype.toFixed()` method,
 which also applies to `toPrecision()`.

 If the `precision` argument is omitted, behaves as
 `Number.prototype.toString()`. If the `precision` argument is a
 non-integer value, it is rounded to the nearest integer.

### Exceptions

`RangeError`

Thrown if `precision` is not between `1` and `100` (inclusive).

Examples
--------

### Using `toPrecision`

```js
let num = 5.123456;

console.log(num.toPrecision()); // '5.123456'
console.log(num.toPrecision(5)); // '5.1235'
console.log(num.toPrecision(2)); // '5.1'
console.log(num.toPrecision(1)); // '5'

num = 0.000123;

console.log(num.toPrecision()); // '0.000123'
console.log(num.toPrecision(5)); // '0.00012300'
console.log(num.toPrecision(2)); // '0.00012'
console.log(num.toPrecision(1)); // '0.0001'

// note that exponential notation might be returned in some circumstances
console.log((1234.5).toPrecision(2)); // '1.2e+3'
```

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

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

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.toString()`


Number.EPSILON - JavaScript

Number.EPSILON
==============

The **`Number.EPSILON`** static data property represents the difference between 1 and the smallest floating point number greater than 1.

Try it
------

Value
-----

2-52, or approximately `2.2204460492503130808472633361816E-16`.

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

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

`Number.EPSILON` is the difference between 1 and the next greater number representable in the Number format, because double precision floating point format only has 52 bits to represent the mantissa, and the lowest bit has a significance of 2-52.

Note that the absolute accuracy of floating numbers decreases as the number gets larger, because the exponent grows while the mantissa's accuracy stays the same. `Number.MIN_VALUE` is the smallest representable positive number, which is much smaller than `Number.EPSILON`.

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

Examples
--------

### Testing equality

Any number encoding system occupying a finite number of bits, of whatever base you choose (e.g. decimal or binary), will *necessarily* be unable to represent all numbers exactly, because you are trying to represent an infinite number of points on the number line using a finite amount of memory. For example, a base-10 (decimal) system cannot represent 1/3 exactly, and a base-2 (binary) system cannot represent `0.1` exactly. Thus, for example, `0.1 + 0.2` is not exactly equal to `0.3`:

```js
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false
```

For this reason, it is often advised that **floating point numbers should never be compared with `===`**. Instead, we can deem two numbers as equal if they are *close enough* to each other. The `Number.EPSILON` constant is usually a reasonable threshold for errors if the arithmetic is around the magnitude of `1`, because `EPSILON`, in essence, specifies how accurate the number "1" is.

```js
function equal(x, y) {
  return Math.abs(x - y) < Number.EPSILON;
}

const x = 0.2;
const y = 0.3;
const z = 0.1;
console.log(equal(x + z, y)); // true
```

However, `Number.EPSILON` is inappropriate for any arithmetic operating on a larger magnitude. If your data is on the 103 order of magnitude, the decimal part will have a much smaller accuracy than `Number.EPSILON`:

```js
function equal(x, y) {
  return Math.abs(x - y) < Number.EPSILON;
}

const x = 1000.1;
const y = 1000.2;
const z = 2000.3;
console.log(x + y); // 2000.3000000000002; error of 10^-13 instead of 10^-16
console.log(equal(x + y, z)); // false
```

In this case, a larger tolerance is required. As the numbers compared have a magnitude of approximately `2000`, a multiplier such as `2000 * Number.EPSILON` creates enough tolerance for this instance.

```js
function equal(x, y, tolerance = Number.EPSILON) {
  return Math.abs(x - y) < tolerance;
}

const x = 1000.1;
const y = 1000.2;
const z = 2000.3;
console.log(equal(x + y, z, 2000 \* Number.EPSILON)); // true
```

In addition to magnitude, it is important to consider the *accuracy* of your input. For example, if the numbers are collected from a form input and the input value can only be adjusted by steps of `0.1` (i.e. `<input type="number" step="0.1">`), it usually makes sense to allow a much larger tolerance, such as `0.01`, since the data only has a precision of `0.1`.

**Note:** Important takeaway: do not simply use `Number.EPSILON` as a threshold for equality testing. Use a threshold that is appropriate for the magnitude and accuracy of the numbers you are comparing.

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

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

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

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

See also
--------

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


Number.NEGATIVE_INFINITY - JavaScript

Number.NEGATIVE\_INFINITY
=========================

The **`Number.NEGATIVE_INFINITY`** static data property represents the negative Infinity value.

Try it
------

Value
-----

The same as the negative value of the global `Infinity` property.

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

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

The `Number.NEGATIVE_INFINITY` value behaves slightly differently than mathematical infinity:

* Any positive value, including `POSITIVE_INFINITY`, multiplied by `NEGATIVE_INFINITY` is `NEGATIVE_INFINITY`.
* Any negative value, including `NEGATIVE_INFINITY`, multiplied by `NEGATIVE_INFINITY` is `POSITIVE_INFINITY`.
* Any positive value divided by `NEGATIVE_INFINITY` is negative zero (as defined in IEEE 754).
* Any negative value divided by `NEGATIVE_INFINITY` is positive zero (as defined in IEEE 754).
* Zero multiplied by `NEGATIVE_INFINITY` is `NaN`.
* `NaN` multiplied by `NEGATIVE_INFINITY` is `NaN`.
* `NEGATIVE_INFINITY`, divided by any negative value except `NEGATIVE_INFINITY`, is `POSITIVE_INFINITY`.
* `NEGATIVE_INFINITY`, divided by any positive value except `POSITIVE_INFINITY`, is `NEGATIVE_INFINITY`.
* `NEGATIVE_INFINITY`, divided by either `NEGATIVE_INFINITY` or `POSITIVE_INFINITY`, is `NaN`.
* `x > Number.NEGATIVE_INFINITY` is true for any number *x* that isn't `NEGATIVE_INFINITY`.

You might use the `Number.NEGATIVE_INFINITY` property to indicate an error condition that returns a finite number in case of success. Note, however, that `NaN` would be more appropriate in such a case.

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

Examples
--------

### Using NEGATIVE\_INFINITY

In the following example, the variable `smallNumber` is assigned a value that is smaller than the minimum value. When the `if` statement executes, `smallNumber` has the value `-Infinity`, so `smallNumber` is set to a more manageable value before continuing.

```js
let smallNumber = -Number.MAX\_VALUE \* 2;

if (smallNumber === Number.NEGATIVE\_INFINITY) {
  smallNumber = returnFinite();
}
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-number.negative\_infinity |

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

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

See also
--------

* `Number.POSITIVE_INFINITY`
* `Number.isFinite()`
* `Infinity`
* `isFinite()`