repo_id
stringlengths
22
103
file_path
stringlengths
41
147
content
stringlengths
181
193k
__index_level_0__
int64
0
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/arraybuffer
data/mdn-content/files/en-us/web/javascript/reference/global_objects/arraybuffer/transfer/index.md
--- title: ArrayBuffer.prototype.transfer() slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/transfer page-type: javascript-instance-method browser-compat: javascript.builtins.ArrayBuffer.transfer --- {{JSRef}} The **`transfer()`** method of {{jsxref("ArrayBuffer")}} instances creates a new `ArrayBuffer` with the same byte content as this buffer, then detaches this buffer. ## Syntax ```js-nolint transfer() transfer(newByteLength) ``` ### Parameters - `newByteLength` {{optional_inline}} - : The {{jsxref("ArrayBuffer/byteLength", "byteLength")}} of the new `ArrayBuffer`. Defaults to the `byteLength` of this `ArrayBuffer`. - If `newByteLength` is smaller than the `byteLength` of this `ArrayBuffer`, the "overflowing" bytes are dropped. - If `newByteLength` is larger than the `byteLength` of this `ArrayBuffer`, the extra bytes are filled with zeros. - If this `ArrayBuffer` is resizable, `newByteLength` must not be greater than its {{jsxref("ArrayBuffer/maxByteLength", "maxByteLength")}}. ### Return value A new {{jsxref("ArrayBuffer")}} object. Its contents are initialized to the contents of this `ArrayBuffer`, and extra bytes, if any, are filled with zeros. The new `ArrayBuffer` is resizable if and only if this `ArrayBuffer` is resizable, in which case its {{jsxref("ArrayBuffer/maxByteLength", "maxByteLength")}} is the same as this `ArrayBuffer`'s. The original `ArrayBuffer` is detached. ### Exceptions - {{jsxref("RangeError")}} - : Thrown if this `ArrayBuffer` is resizable and `newByteLength` is greater than the {{jsxref("ArrayBuffer/maxByteLength", "maxByteLength")}} of this `ArrayBuffer`. - {{jsxref("TypeError")}} - : Thrown if this `ArrayBuffer` is already detached. ## Description The `transfer()` method performs the same operation as the [structured clone algorithm](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). It copies the bytes of this `ArrayBuffer` into a new `ArrayBuffer` object, then detaches this `ArrayBuffer` object. See [transferring ArrayBuffers](/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer#transferring_arraybuffers) for more information. `transfer()` preserves the resizability of this `ArrayBuffer`. If you want the new `ArrayBuffer` to be non-resizable, use {{jsxref("ArrayBuffer/transferToFixedLength", "transferToFixedLength()")}} instead. There's no way to transfer a buffer that makes a fixed-length buffer become resizable. `transfer()` is very efficient because implementations may implement this method as a zero-copy move or a `realloc` — there does not need to be an actual copy of the data. ## Examples ### Transferring an ArrayBuffer ```js // Create an ArrayBuffer and write a few bytes const buffer = new ArrayBuffer(8); const view = new Uint8Array(buffer); view[1] = 2; view[7] = 4; // Copy the buffer to the same size const buffer2 = buffer.transfer(); console.log(buffer.detached); // true console.log(buffer2.byteLength); // 8 const view2 = new Uint8Array(buffer2); console.log(view2[1]); // 2 console.log(view2[7]); // 4 // Copy the buffer to a smaller size const buffer3 = buffer2.transfer(4); console.log(buffer3.byteLength); // 4 const view3 = new Uint8Array(buffer3); console.log(view3[1]); // 2 console.log(view3[7]); // undefined // Copy the buffer to a larger size const buffer4 = buffer3.transfer(8); console.log(buffer4.byteLength); // 8 const view4 = new Uint8Array(buffer4); console.log(view4[1]); // 2 console.log(view4[7]); // 0 // Already detached, throws TypeError buffer.transfer(); // TypeError: Cannot perform ArrayBuffer.prototype.transfer on a detached ArrayBuffer ``` ### Transferring a resizable ArrayBuffer ```js const buffer = new ArrayBuffer(8, { maxByteLength: 16 }); const view = new Uint8Array(buffer); view[1] = 2; view[7] = 4; // Copy the buffer to a smaller size const buffer2 = buffer.transfer(4); console.log(buffer2.byteLength); // 4 console.log(buffer2.maxByteLength); // 16 const view2 = new Uint8Array(buffer2); console.log(view2[1]); // 2 console.log(view2[7]); // undefined buffer2.resize(8); console.log(view2[7]); // 0 // Copy the buffer to a larger size within maxByteLength const buffer3 = buffer2.transfer(12); console.log(buffer3.byteLength); // 12 // Copy the buffer to a larger size than maxByteLength buffer3.transfer(20); // RangeError: Invalid array buffer length ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `ArrayBuffer.prototype.transfer()` in `core-js`](https://github.com/zloirock/core-js#arraybufferprototypetransfer-and-friends) - {{jsxref("ArrayBuffer")}} - {{jsxref("ArrayBuffer.prototype.detached")}} - {{jsxref("ArrayBuffer.prototype.transferToFixedLength()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/arraybuffer
data/mdn-content/files/en-us/web/javascript/reference/global_objects/arraybuffer/slice/index.md
--- title: ArrayBuffer.prototype.slice() slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/slice page-type: javascript-instance-method browser-compat: javascript.builtins.ArrayBuffer.slice --- {{JSRef}} The **`slice()`** method of {{jsxref("ArrayBuffer")}} instances returns a new `ArrayBuffer` whose contents are a copy of this `ArrayBuffer`'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. {{EmbedInteractiveExample("pages/js/arraybuffer-slice.html")}} ## Syntax ```js-nolint slice() slice(start) slice(start, end) ``` ### Parameters - `start` {{optional_inline}} - : Zero-based index at which to start extraction, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). - Negative index counts back from the end of the buffer — if `-buffer.length <= 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_inline}} - : Zero-based index at which to end extraction, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). `slice()` extracts up to but not including `end`. - Negative index counts back from the end of the buffer — if `-buffer.length <= 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` implies a position before or at the position that `start` implies, nothing is extracted. ### Return value A new {{jsxref("ArrayBuffer")}} containing the extracted elements. ## Examples ### Copying an ArrayBuffer ```js const buf1 = new ArrayBuffer(8); const buf2 = buf1.slice(0); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("ArrayBuffer")}} - {{jsxref("SharedArrayBuffer.prototype.slice()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/arraybuffer
data/mdn-content/files/en-us/web/javascript/reference/global_objects/arraybuffer/detached/index.md
--- title: ArrayBuffer.prototype.detached slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/detached page-type: javascript-instance-accessor-property browser-compat: javascript.builtins.ArrayBuffer.detached --- {{JSRef}} The **`detached`** accessor property of {{jsxref("ArrayBuffer")}} instances returns a boolean indicating whether or not this buffer has been detached (transferred). ## Description The `detached` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is `false` when the `ArrayBuffer` is first created. The value becomes `true` if the `ArrayBuffer` is [transferred](/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer#transferring_arraybuffers), which detaches the instance from its underlying memory. Once a buffer becomes detached, it is no longer usable. ## Examples ### Using detached ```js const buffer = new ArrayBuffer(8); console.log(buffer.detached); // false const newBuffer = buffer.transfer(); console.log(buffer.detached); // true console.log(newBuffer.detached); // false ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `ArrayBuffer.prototype.detached` in `core-js`](https://github.com/zloirock/core-js#arraybufferprototypetransfer-and-friends) - {{jsxref("ArrayBuffer")}} - {{jsxref("ArrayBuffer.prototype.transfer()")}} - {{jsxref("ArrayBuffer.prototype.transferToFixedLength()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/arraybuffer
data/mdn-content/files/en-us/web/javascript/reference/global_objects/arraybuffer/arraybuffer/index.md
--- title: ArrayBuffer() constructor slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/ArrayBuffer page-type: javascript-constructor browser-compat: javascript.builtins.ArrayBuffer.ArrayBuffer --- {{JSRef}} The **`ArrayBuffer()`** constructor creates {{jsxref("ArrayBuffer")}} objects. {{EmbedInteractiveExample("pages/js/arraybuffer-constructor.html", "shorter")}} ## Syntax ```js-nolint new ArrayBuffer(length) new ArrayBuffer(length, options) ``` > **Note:** `ArrayBuffer()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}. ### Parameters - `length` - : The size, in bytes, of the array buffer to create. - `options` {{optional_inline}} - : An object, which can contain the following properties: - `maxByteLength` {{optional_inline}} - : The maximum size, in bytes, that the array buffer can be resized to. ### Return value A new `ArrayBuffer` object of the specified size, with its {{jsxref("ArrayBuffer/maxByteLength", "maxByteLength")}} property set to the specified `maxByteLength` if one was specified. Its contents are initialized to 0. ### Exceptions - {{jsxref("RangeError")}} - : Thrown in one of the following cases: - `length` or `maxByteLength` is larger than {{jsxref("Number.MAX_SAFE_INTEGER")}} (≥ 2<sup>53</sup>) or negative. - `length` is larger than `maxByteLength`. ## Examples ### Creating an ArrayBuffer In this example, we create a 8-byte buffer with a {{jsxref("Int32Array")}} view referring to the buffer: ```js const buffer = new ArrayBuffer(8); const view = new Int32Array(buffer); ``` ### Creating a resizable ArrayBuffer In this example, we create a 8-byte buffer that is resizable to a max length of 16 bytes, then {{jsxref("ArrayBuffer/resize", "resize()")}} it to 12 bytes: ```js const buffer = new ArrayBuffer(8, { maxByteLength: 16 }); buffer.resize(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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `ArrayBuffer` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays) - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("SharedArrayBuffer")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/arraybuffer
data/mdn-content/files/en-us/web/javascript/reference/global_objects/arraybuffer/resize/index.md
--- title: ArrayBuffer.prototype.resize() slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/resize page-type: javascript-instance-method browser-compat: javascript.builtins.ArrayBuffer.resize --- {{JSRef}} The **`resize()`** method of {{jsxref("ArrayBuffer")}} instances resizes the `ArrayBuffer` to the specified size, in bytes. {{EmbedInteractiveExample("pages/js/arraybuffer-resize.html")}} ## Syntax ```js-nolint resize(newLength) ``` ### Parameters - `newLength` - : The new length, in bytes, to resize the `ArrayBuffer` to. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - {{jsxref("TypeError")}} - : Thrown if the `ArrayBuffer` is detached or is not resizable. - {{jsxref("RangeError")}} - : Thrown if `newLength` is larger than the {{jsxref("ArrayBuffer/maxByteLength", "maxByteLength")}} of the `ArrayBuffer`. ## Description The `resize()` method resizes an `ArrayBuffer` to the size specified by the `newLength` parameter, provided that the `ArrayBuffer` is [resizable](/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/resizable) and the new size is less than or equal to the {{jsxref("ArrayBuffer/maxByteLength", "maxByteLength")}} of the `ArrayBuffer`. New bytes are initialized to 0. Note that you can use `resize()` to shrink as well as grow an `ArrayBuffer` — it is permissible for `newLength` to be smaller than the `ArrayBuffer`'s current {{jsxref("ArrayBuffer/byteLength", "byteLength")}}. ## Examples ### Using resize() In this example, we create a 8-byte buffer that is resizable to a max length of 16 bytes, then check its `resizable` property, resizing it if `resizable` returns `true`: ```js const buffer = new ArrayBuffer(8, { maxByteLength: 16 }); if (buffer.resizable) { console.log("Buffer is resizable!"); buffer.resize(12); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("ArrayBuffer")}} - {{jsxref("ArrayBuffer.prototype.resizable")}} - {{jsxref("ArrayBuffer.prototype.maxByteLength")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/arraybuffer
data/mdn-content/files/en-us/web/javascript/reference/global_objects/arraybuffer/transfertofixedlength/index.md
--- title: ArrayBuffer.prototype.transferToFixedLength() slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/transferToFixedLength page-type: javascript-instance-method browser-compat: javascript.builtins.ArrayBuffer.transferToFixedLength --- {{JSRef}} The **`transferToFixedLength()`** method of {{jsxref("ArrayBuffer")}} instances creates a new non-resizable `ArrayBuffer` with the same byte content as this buffer, then detaches this buffer. ## Syntax ```js-nolint transferToFixedLength() transferToFixedLength(newByteLength) ``` ### Parameters - `newByteLength` - : The {{jsxref("ArrayBuffer/byteLength", "byteLength")}} of the new `ArrayBuffer`. Defaults to the `byteLength` of this `ArrayBuffer`. - If `newByteLength` is smaller than the `byteLength` of this `ArrayBuffer`, the "overflowing" bytes are dropped. - If `newByteLength` is larger than the `byteLength` of this `ArrayBuffer`, the extra bytes are filled with zeros. ### Return value A new {{jsxref("ArrayBuffer")}} object. Its contents are initialized to the contents of this `ArrayBuffer`, and extra bytes, if any, are filled with zeros. The new `ArrayBuffer` is always non-resizable. The original `ArrayBuffer` is detached. ### Exceptions - {{jsxref("TypeError")}} - : Thrown if this `ArrayBuffer` is already detached. ## Description Unlike {{jsxref("ArrayBuffer/transfer", "transfer()")}}, `transferToFixedLength()` always creates a non-resizable `ArrayBuffer`. This means `newByteLength` can be larger than the `maxByteLength`, even if this `ArrayBuffer` is resizable. See [transferring ArrayBuffers](/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer#transferring_arraybuffers) for more information. ## Examples ### Transferring a resizable ArrayBuffer to fixed-length ```js const buffer = new ArrayBuffer(8, { maxByteLength: 16 }); const view = new Uint8Array(buffer); view[1] = 2; view[7] = 4; const buffer2 = buffer.transferToFixedLength(); console.log(buffer2.byteLength); // 8 console.log(buffer2.resizable); // false const view2 = new Uint8Array(buffer2); console.log(view2[1]); // 2 console.log(view2[7]); // 4 ``` Using `transferToFixedLength`, `newByteLength` can be larger than the `maxByteLength` of the original `ArrayBuffer`. ```js const buffer = new ArrayBuffer(8, { maxByteLength: 16 }); const view = new Uint8Array(buffer); view[1] = 2; view[7] = 4; const buffer2 = buffer.transferToFixedLength(20); console.log(buffer2.byteLength); // 20 console.log(buffer2.resizable); // false const view2 = new Uint8Array(buffer2); console.log(view2[1]); // 2 console.log(view2[7]); // 4 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `ArrayBuffer.prototype.transferToFixedLength()` in `core-js`](https://github.com/zloirock/core-js#arraybufferprototypetransfer-and-friends) - {{jsxref("ArrayBuffer")}} - {{jsxref("ArrayBuffer.prototype.detached")}} - {{jsxref("ArrayBuffer.prototype.transfer()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/arraybuffer
data/mdn-content/files/en-us/web/javascript/reference/global_objects/arraybuffer/bytelength/index.md
--- title: ArrayBuffer.prototype.byteLength slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/byteLength page-type: javascript-instance-accessor-property browser-compat: javascript.builtins.ArrayBuffer.byteLength --- {{JSRef}} The **`byteLength`** accessor property of {{jsxref("ArrayBuffer")}} instances returns the length (in bytes) of this array buffer. {{EmbedInteractiveExample("pages/js/arraybuffer-bytelength.html")}} ## 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 array is constructed and cannot be changed. This property returns 0 if this `ArrayBuffer` has been detached. ## Examples ### Using byteLength ```js const buffer = new ArrayBuffer(8); buffer.byteLength; // 8 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("ArrayBuffer")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/arraybuffer
data/mdn-content/files/en-us/web/javascript/reference/global_objects/arraybuffer/maxbytelength/index.md
--- title: ArrayBuffer.prototype.maxByteLength slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/maxByteLength page-type: javascript-instance-accessor-property browser-compat: javascript.builtins.ArrayBuffer.maxByteLength --- {{JSRef}} The **`maxByteLength`** accessor property of {{jsxref("ArrayBuffer")}} instances returns the maximum length (in bytes) that this array buffer can be resized to. {{EmbedInteractiveExample("pages/js/arraybuffer-maxbytelength.html")}} ## 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 array is constructed, set via the `maxByteLength` option of the {{jsxref("ArrayBuffer/ArrayBuffer", "ArrayBuffer()")}} constructor, and cannot be changed. This property returns 0 if this `ArrayBuffer` has been detached. If this `ArrayBuffer` was constructed without specifying a `maxByteLength` value, this property returns a value equal to the value of the `ArrayBuffer`'s {{jsxref("ArrayBuffer/byteLength", "byteLength")}}. ## Examples ### Using maxByteLength In this example, we create an 8-byte buffer that is resizable to a max length of 16 bytes, then return its `maxByteLength`: ```js const buffer = new ArrayBuffer(8, { maxByteLength: 16 }); buffer.maxByteLength; // 16 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("ArrayBuffer")}} - {{jsxref("ArrayBuffer.prototype.byteLength")}} - {{jsxref("ArrayBuffer.prototype.resize()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/arraybuffer
data/mdn-content/files/en-us/web/javascript/reference/global_objects/arraybuffer/@@species/index.md
--- title: ArrayBuffer[@@species] slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/@@species page-type: javascript-static-accessor-property browser-compat: javascript.builtins.ArrayBuffer.@@species --- {{JSRef}} The **`ArrayBuffer[@@species]`** static accessor property returns the constructor used to construct return values from array buffer 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](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js-nolint ArrayBuffer[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 buffers. ## Description The `@@species` accessor property returns the default constructor for `ArrayBuffer` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class ArrayBuffer { 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 ArrayBuffer {} SubArrayBuffer[Symbol.species] === SubArrayBuffer; // true ``` When calling array buffer methods that do not mutate the existing object but return a new array buffer instance (for example, [`slice()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/slice)), the object'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 `ArrayBuffer` constructor for `ArrayBuffer`. ```js ArrayBuffer[Symbol.species]; // function ArrayBuffer() ``` ### Species in derived objects In an instance of a custom `ArrayBuffer` subclass, such as `MyArrayBuffer`, the `MyArrayBuffer` species is the `MyArrayBuffer` constructor. However, you might want to overwrite this, in order to return parent `ArrayBuffer` objects in your derived class methods: ```js class MyArrayBuffer extends ArrayBuffer { // Overwrite MyArrayBuffer species to the parent ArrayBuffer constructor static get [Symbol.species]() { return ArrayBuffer; } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("ArrayBuffer")}} - {{jsxref("Symbol.species")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/arraybuffer
data/mdn-content/files/en-us/web/javascript/reference/global_objects/arraybuffer/isview/index.md
--- title: ArrayBuffer.isView() slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView page-type: javascript-static-method browser-compat: javascript.builtins.ArrayBuffer.isView --- {{JSRef}} The **`ArrayBuffer.isView()`** static method determines whether the passed value is one of the `ArrayBuffer` views, such as [typed array objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) or a {{jsxref("DataView")}}. {{EmbedInteractiveExample("pages/js/arraybuffer-isview.html", "shorter")}} ## Syntax ```js-nolint ArrayBuffer.isView(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if the given argument is one of the {{jsxref("ArrayBuffer")}} views; otherwise, `false`. ## Examples ### Using isView ```js ArrayBuffer.isView(); // false ArrayBuffer.isView([]); // false ArrayBuffer.isView({}); // false ArrayBuffer.isView(null); // false ArrayBuffer.isView(undefined); // false ArrayBuffer.isView(new ArrayBuffer(10)); // false ArrayBuffer.isView(new Uint8Array()); // true ArrayBuffer.isView(new Float32Array()); // true ArrayBuffer.isView(new Int8Array(10).subarray(0, 3)); // true const buffer = new ArrayBuffer(2); const dv = new DataView(buffer); ArrayBuffer.isView(dv); // true ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/isfinite/index.md
--- title: isFinite() slug: Web/JavaScript/Reference/Global_Objects/isFinite page-type: javascript-function browser-compat: javascript.builtins.isFinite --- {{jsSidebar("Objects")}} The **`isFinite()`** function determines whether a value is finite, first converting the value to a number if necessary. A finite number is one that's not {{jsxref("NaN")}} or ±{{jsxref("Infinity")}}. Because coercion inside the `isFinite()` function can be [surprising](/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN#description), you may prefer to use {{jsxref("Number.isFinite()")}}. {{EmbedInteractiveExample("pages/js/globalprops-isfinite.html")}} ## Syntax ```js-nolint isFinite(value) ``` ### Parameters - `value` - : The value to be tested. ### Return value `false` if the given value is {{jsxref("NaN")}}, {{jsxref("Infinity")}}, or `-Infinity` after being [converted to a number](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion); otherwise, `true`. ## Description `isFinite()` is a function property of the global object. When the argument to the `isFinite()` function is not of type [Number](/en-US/docs/Web/JavaScript/Data_structures#number_type), the value is first coerced to a number, and the resulting value is then compared against `NaN` and ±Infinity. This is as confusing as the behavior of {{jsxref("isNaN")}} — for example, `isFinite("1")` is `true`. {{jsxref("Number.isFinite()")}} is a more reliable way to test whether a value is a finite number value, because it returns `false` for any non-number input. ## Examples ### Using isFinite() ```js isFinite(Infinity); // false isFinite(NaN); // false isFinite(-Infinity); // false isFinite(0); // true isFinite(2e64); // true isFinite(910); // true // Would've been false with the more robust Number.isFinite(): isFinite(null); // true isFinite("0"); // true ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Number.isFinite()")}} - {{jsxref("Number.NaN")}} - {{jsxref("Number.POSITIVE_INFINITY")}} - {{jsxref("Number.NEGATIVE_INFINITY")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/asyncgenerator/index.md
--- title: AsyncGenerator slug: Web/JavaScript/Reference/Global_Objects/AsyncGenerator page-type: javascript-class browser-compat: javascript.builtins.AsyncGenerator --- {{JSRef}} The **`AsyncGenerator`** object is returned by an {{jsxref("Statements/async_function*", "async generator function", "", 1)}} and it conforms to both the [async iterable protocol and the async iterator protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols). Async generator methods always yield {{jsxref("Promise")}} objects. `AsyncGenerator` is a subclass of the hidden {{jsxref("AsyncIterator")}} class. {{EmbedInteractiveExample("pages/js/expressions-async-function-asterisk.html", "taller")}} ## Constructor The `AsyncGenerator` constructor is not available globally. Instances of `AsyncGenerator` must be returned from [async generator functions](/en-US/docs/Web/JavaScript/Reference/Statements/async_function*) ```js async function* createAsyncGenerator() { yield await Promise.resolve(1); yield await Promise.resolve(2); yield await Promise.resolve(3); } const asyncGen = createAsyncGenerator(); asyncGen.next().then((res) => console.log(res.value)); // 1 asyncGen.next().then((res) => console.log(res.value)); // 2 asyncGen.next().then((res) => console.log(res.value)); // 3 ``` In fact, there's no JavaScript entity that corresponds to the `AsyncGenerator` constructor. There's only a hidden object which is the prototype object shared by all objects created by async generator functions. This object is often stylized as `AsyncGenerator.prototype` to make it look like a class, but it should be more appropriately called [`AsyncGeneratorFunction.prototype.prototype`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGeneratorFunction), because `AsyncGeneratorFunction` is an actual JavaScript entity. ## Instance properties These properties are defined on `AsyncGenerator.prototype` and shared by all `AsyncGenerator` instances. - {{jsxref("Object/constructor", "AsyncGenerator.prototype.constructor")}} - : The constructor function that created the instance object. For `AsyncGenerator` instances, the initial value is [`AsyncGeneratorFunction.prototype`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGeneratorFunction). > **Note:** `AsyncGenerator` objects do not store a reference to the async generator function that created them. - `AsyncGenerator.prototype[@@toStringTag]` - : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"AsyncGenerator"`. This property is used in {{jsxref("Object.prototype.toString()")}}. ## Instance methods _Also inherits instance methods from its parent {{jsxref("AsyncIterator")}}_. - {{jsxref("AsyncGenerator.prototype.next()")}} - : Returns a {{jsxref("Promise")}} which will be resolved with the given value yielded by the {{jsxref("Operators/yield", "yield")}} expression. - {{jsxref("AsyncGenerator.prototype.return()")}} - : Acts as if a `return` statement is inserted in the generator's body at the current suspended position, which finishes the generator and allows the generator to perform any cleanup tasks when combined with a [`try...finally`](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch#the_finally_block) block. - {{jsxref("AsyncGenerator.prototype.throw()")}} - : Acts as if a `throw` statement is inserted in the generator's body at the current suspended position, which informs the generator of an error condition and allows it to handle the error, or perform cleanup and close itself. ## Examples ### Async generator iteration The following example iterates over an async generator, logging values 1–6 to the console at decreasing time intervals. Notice how each time a Promise is yielded, but it's automatically resolved within the `for await...of` loop. ```js // An async task. Pretend it's doing something more useful // in practice. function delayedValue(time, value) { return new Promise((resolve /*, reject*/) => { setTimeout(() => resolve(value), time); }); } async function* generate() { yield delayedValue(2000, 1); yield delayedValue(100, 2); yield delayedValue(500, 3); yield delayedValue(250, 4); yield delayedValue(125, 5); yield delayedValue(50, 6); console.log("All done!"); } async function main() { for await (const value of generate()) { console.log("value", value); } } main().catch((e) => console.error(e)); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Statements/function*", "function*", "", 1)}} - {{jsxref("Statements/async_function*", "async function*", "", 1)}} - [`function*` expression](/en-US/docs/Web/JavaScript/Reference/Operators/function*) - {{jsxref("GeneratorFunction", "Generator Function", "", 1)}} - {{jsxref("AsyncGeneratorFunction", "Async Generator Function", "", 1)}} - [Iterators and generators](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators) guide
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/asyncgenerator
data/mdn-content/files/en-us/web/javascript/reference/global_objects/asyncgenerator/return/index.md
--- title: AsyncGenerator.prototype.return() slug: Web/JavaScript/Reference/Global_Objects/AsyncGenerator/return page-type: javascript-instance-method browser-compat: javascript.builtins.AsyncGenerator.return --- {{JSRef}} The **`return()`** method of {{jsxref("AsyncGenerator")}} instances acts as if a `return` statement is inserted in the generator's body at the current suspended position, which finishes the generator and allows the generator to perform any cleanup tasks when combined with a [`try...finally`](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch#the_finally_block) block. ## Syntax ```js-nolint asyncGeneratorInstance.return() asyncGeneratorInstance.return(value) ``` ### Parameters - `value` {{optional_inline}} - : The value to return. ### Return value A {{jsxref("Promise")}} which resolves with an {{jsxref("Object")}} with two properties: - `done` - : A boolean value: - `true` if the generator function's control flow has reached the end. - `false` if the generator function's control flow hasn't reached the end and can produce more values. This can only happen if the `return` is captured in a [`try...finally`](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch#the_finally_block) and there are more `yield` expressions in the `finally` block. - `value` - : The value that is given as an argument, or, if the `yield` expression is wrapped in a [`try...finally`](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch#the_finally_block), the value yielded/returned from the `finally` block. ## Description The `return()` method, when called, can be seen as if a `return value;` statement is inserted in the generator's body at the current suspended position, where `value` is the value passed to the `return()` method. Therefore, in a typical flow, calling `return(value)` will return `{ done: true, value: value }`. However, if the `yield` expression is wrapped in a `try...finally` block, the control flow doesn't exit the function body, but proceeds to the `finally` block instead. In this case, the value returned may be different, and `done` may even be `false`, if there are more `yield` expressions within the `finally` block. ## Examples ### Using return() The following example shows a simple async generator and the `return` method. ```js // An async task. Pretend it's doing something more useful // in practice. function delayedValue(time, value) { return new Promise((resolve, reject) => { setTimeout(() => resolve(value), time); }); } async function* createAsyncGenerator() { yield delayedValue(500, 1); yield delayedValue(500, 2); yield delayedValue(500, 3); } const asyncGen = createAsyncGenerator(); asyncGen.next().then((res) => console.log(res)); // { value: 1, done: false } asyncGen.return("foo").then((res) => console.log(res)); // { value: "foo", done: true } asyncGen.next().then((res) => console.log(res)); // { value: undefined, done: true } ``` ### Using return() once a generator is complete If no `value` argument is passed into the `return()` method, the promise will resolve as if the [next()](/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator/next) method has been called. In this example the generator has completed, so the value returned is `undefined`. `return()` can still be called after the generator is in a "completed" state, however the generator will stay in this state. ```js async function* createAsyncGenerator() { yield await Promise.resolve(1); yield await Promise.resolve(2); yield await Promise.resolve(3); } const asyncGen = createAsyncGenerator(); asyncGen.next().then((res) => console.log(res)); // { value: 1, done: false } asyncGen.next().then((res) => console.log(res)); // { value: 2, done: false } asyncGen.next().then((res) => console.log(res)); // { value: 3, done: false } // value is returned undefined, as no value is passed and generator is 'done' asyncGen.return().then((res) => console.log(res)); // { value: undefined, done: true } // we can still return a value once the generator is complete asyncGen.return(1).then((res) => console.log(res)); // { value: 1, done: true } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Statements/async_function*", "async function*")}} - [Iterators and generators](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators) guide
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/asyncgenerator
data/mdn-content/files/en-us/web/javascript/reference/global_objects/asyncgenerator/throw/index.md
--- title: AsyncGenerator.prototype.throw() slug: Web/JavaScript/Reference/Global_Objects/AsyncGenerator/throw page-type: javascript-instance-method browser-compat: javascript.builtins.AsyncGenerator.throw --- {{JSRef}} The **`throw()`** method of {{jsxref("AsyncGenerator")}} instances acts as if a `throw` statement is inserted in the generator's body at the current suspended position, which informs the generator of an error condition and allows it to handle the error, or perform cleanup and close itself. ## Syntax ```js-nolint asyncGeneratorInstance.throw(exception) ``` ### Parameters - `exception` - : The exception to throw. For debugging purposes, it is useful to make it an `instanceof` {{jsxref("Error")}}. ### Return value If the thrown error is not caught, it will return a {{jsxref("Promise")}} which rejects with the exception passed in. If the exception is caught by a [`try...catch`](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch) and the generator resumes to yield more values, it will return a {{jsxref("Promise")}} which resolves with an {{jsxref("Object")}} with two properties: - `done` - : A boolean value: - `true` if the generator function's control flow has reached the end. - `false` if the generator function is able to produce more values. - `value` - : The value yielded from the next `yield` expression. ## Examples ### Using throw() The following example shows a simple generator and an error that is thrown using the `throw` method. An error can be caught by a {{jsxref("Statements/try...catch", "try...catch")}} block as usual. ```js // An async task. Pretend it's doing something more useful // in practice. function sleep(time) { return new Promise((resolve, reject) => { setTimeout(resolve, time); }); } async function* createAsyncGenerator() { while (true) { try { await sleep(500); yield 42; } catch (e) { console.error(e); } } } const asyncGen = createAsyncGenerator(); asyncGen.next(1).then((res) => console.log(res)); // { value: 42, done: false } asyncGen .throw(new Error("Something went wrong")) // Error: Something went wrong .then((res) => console.log(res)); // { value: 42, done: false } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Statements/async_function*", "async function*")}} - [Iterators and generators](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators) guide
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/asyncgenerator
data/mdn-content/files/en-us/web/javascript/reference/global_objects/asyncgenerator/next/index.md
--- title: AsyncGenerator.prototype.next() slug: Web/JavaScript/Reference/Global_Objects/AsyncGenerator/next page-type: javascript-instance-method browser-compat: javascript.builtins.AsyncGenerator.next --- {{JSRef}} The **`next()`** method of {{jsxref("AsyncGenerator")}} instances returns the next value in the sequence. ## Syntax ```js-nolint next() next(value) ``` ### Parameters - `value` {{optional_inline}} - : An optional value used to modify the internal state of the generator. A value passed to the `next()` method will be received by `yield` ### Return value A {{jsxref("Promise")}} which when resolved returns an {{jsxref("Object")}} with two properties: - `done` - : A boolean value: - `true` if the generator is past the end of its control flow. In this case `value` specifies the _return value_ of the generator (which may be undefined). - `false` if the generator is able to produce more values. - `value` - : Any JavaScript value yielded or returned by the generator. ## Examples ### Using next() The following example shows a simple generator and the object that the `next` method returns: ```js // An async task. Pretend it's doing something more useful // in practice. function delayedValue(time, value) { return new Promise((resolve, reject) => { setTimeout(() => resolve(value), time); }); } async function* createAsyncGenerator() { yield delayedValue(500, 1); yield delayedValue(500, 2); yield delayedValue(500, 3); } const asyncGen = createAsyncGenerator(); asyncGen.next().then((res) => console.log(res)); // { value: 1, done: false } asyncGen.next().then((res) => console.log(res)); // { value: 2, done: false } asyncGen.next().then((res) => console.log(res)); // { value: 3, done: false } asyncGen.next().then((res) => console.log(res)); // { value: undefined, done: true } ``` ### Sending values to the generator In this example, `next` is called with a value. > **Note:** The first call does not log anything, because the generator was not yielding anything initially. ```js // An async task. Pretend it's doing something more useful // in practice. function sleep(time) { return new Promise((resolve, reject) => { setTimeout(resolve, time); }); } async function* createAsyncGenerator() { while (true) { await sleep(500); const value = yield; console.log(value); } } async function main() { const asyncGen = createAsyncGenerator(); // No log at this step: the first value sent through `next` is lost console.log(await asyncGen.next(1)); // { value: undefined, done: false } // Logs 2: the value sent through `next` console.log(await asyncGen.next(2)); // { value: undefined, done: false } } main(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Statements/async_function*", "async function*")}} - [Iterators and generators](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators) guide
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/internalerror/index.md
--- title: InternalError slug: Web/JavaScript/Reference/Global_Objects/InternalError page-type: javascript-class status: - non-standard browser-compat: javascript.builtins.InternalError --- {{JSRef}}{{Non-standard_Header}} The **`InternalError`** object indicates an error that occurred internally in the JavaScript engine. Example cases are mostly when something is too large, e.g.: - "too many switch cases", - "too many parentheses in regular expression", - "array initializer too large", - "too much recursion". `InternalError` is a subclass of {{jsxref("Error")}}. ## Constructor - {{jsxref("InternalError/InternalError", "InternalError()")}} {{non-standard_inline}} - : Creates a new `InternalError` object. ## Instance properties _Also inherits instance properties from its parent {{jsxref("Error")}}_. These properties are defined on `InternalError.prototype` and shared by all `InternalError` instances. - {{jsxref("Object/constructor", "InternalError.prototype.constructor")}} - : The constructor function that created the instance object. For `InternalError` instances, the initial value is the {{jsxref("InternalError/InternalError", "InternalError")}} constructor. - {{jsxref("Error/name", "InternalError.prototype.name")}} - : Represents the name for the type of error. For `InternalError.prototype.name`, the initial value is `"InternalError"`. ## Instance methods _Inherits instance methods from its parent {{jsxref("Error")}}_. ## Examples ### Too much recursion This recursive function runs 10 times, as per the exit condition. ```js function loop(x) { // "x >= 10" is the exit condition if (x >= 10) return; // do stuff loop(x + 1); // the recursive call } loop(0); ``` Setting this condition to an extremely high value, may not work: ```js example-bad function loop(x) { if (x >= 1000000000000) return; // do stuff loop(x + 1); } loop(0); // InternalError: too much recursion ``` For more information, see [InternalError: too much recursion.](/en-US/docs/Web/JavaScript/Reference/Errors/Too_much_recursion) ## Specifications Not part of any standard. ## Browser compatibility {{Compat}} ## See also - {{jsxref("Error")}} - [InternalError: too much recursion](/en-US/docs/Web/JavaScript/Reference/Errors/Too_much_recursion)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/internalerror
data/mdn-content/files/en-us/web/javascript/reference/global_objects/internalerror/internalerror/index.md
--- title: InternalError() constructor slug: Web/JavaScript/Reference/Global_Objects/InternalError/InternalError page-type: javascript-constructor status: - non-standard browser-compat: javascript.builtins.InternalError.InternalError --- {{JSRef}}{{Non-standard_Header}} The **`InternalError()`** constructor creates {{jsxref("InternalError")}} objects. ## Syntax ```js-nolint 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`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Both create a new `InternalError` instance. ### Parameters - `message` {{optional_inline}} - : Human-readable description of the error. - `options` {{optional_inline}} - : An object that has the following properties: - `cause` {{optional_inline}} - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. - `fileName` {{optional_inline}} {{non-standard_inline}} - : The name of the file containing the code that caused the exception - `lineNumber` {{optional_inline}} {{non-standard_inline}} - : The line number of the code that caused the exception ## Examples ### Creating a new InternalError ```js new InternalError("Engine failure"); ``` ## Specifications Not part of any standard. ## Browser compatibility {{Compat}} ## See also - {{jsxref("Error")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/encodeuricomponent/index.md
--- title: encodeURIComponent() slug: Web/JavaScript/Reference/Global_Objects/encodeURIComponent page-type: javascript-function browser-compat: javascript.builtins.encodeURIComponent --- {{jsSidebar("Objects")}} The **`encodeURIComponent()`** function encodes a {{Glossary("URI")}} by replacing each instance of certain characters by one, two, three, or four escape sequences representing the {{Glossary("UTF-8")}} encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to {{jsxref("encodeURI()")}}, this function encodes more characters, including those that are part of the URI syntax. {{EmbedInteractiveExample("pages/js/globalprops-encodeuricomponent.html", "shorter")}} ## Syntax ```js-nolint encodeURIComponent(uriComponent) ``` ### Parameters - `uriComponent` - : A string to be encoded as a URI component (a path, query string, fragment, etc.). Other values are [converted to strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). ### Return value A new string representing the provided `uriComponent` encoded as a URI component. ### Exceptions - {{jsxref("URIError")}} - : Thrown if `uriComponent` contains a [lone surrogate](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_code_points_and_grapheme_clusters). ## Description `encodeURIComponent()` is a function property of the global object. `encodeURIComponent()` uses the same encoding algorithm as described in {{jsxref("encodeURI()")}}. It escapes all characters **except**: ```plain A–Z a–z 0–9 - _ . ! ~ * ' ( ) ``` Compared to {{jsxref("encodeURI()")}}, `encodeURIComponent()` escapes a larger set of characters. Use `encodeURIComponent()` on user-entered fields from forms {{HTTPMethod("POST")}}'d to the server — this will encode `&` symbols that may inadvertently be generated during data entry for special HTML entities or other characters that require encoding/decoding. For example, if a user writes `Jack & Jill`, without `encodeURIComponent()`, the ampersand could be interpreted on the server as the start of a new field and jeopardize the integrity of the data. For [`application/x-www-form-urlencoded`](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#application/x-www-form-urlencoded-encoding-algorithm), spaces are to be replaced by `+`, so one may wish to follow a `encodeURIComponent()` replacement with an additional replacement of `%20` with `+`. ## Examples ### Encoding for Content-Disposition and Link headers The following example provides the special encoding required within UTF-8 {{HTTPHeader("Content-Disposition")}} and {{HTTPHeader("Link")}} server response header parameters (e.g., UTF-8 filenames): ```js const fileName = "my file(2).txt"; const header = `Content-Disposition: attachment; filename*=UTF-8''${encodeRFC5987ValueChars( fileName, )}`; console.log(header); // "Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt" function encodeRFC5987ValueChars(str) { return ( encodeURIComponent(str) // The following creates the sequences %27 %28 %29 %2A (Note that // the valid encoding of "*" is %2A, which necessitates calling // toUpperCase() to properly encode). Although RFC3986 reserves "!", // RFC5987 does not, so we do not need to escape it. .replace( /['()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, ) // The following are not required for percent-encoding per RFC5987, // so we can allow for a little better readability over the wire: |`^ .replace(/%(7C|60|5E)/g, (str, hex) => String.fromCharCode(parseInt(hex, 16)), ) ); } ``` ### Encoding for RFC3986 The more recent [RFC3986](https://datatracker.ietf.org/doc/html/rfc3986) reserves !, ', (, ), and \*, even though these characters have no formalized URI delimiting uses. The following function encodes a string for RFC3986-compliant URL component format. It also encodes [ and ], which are part of the {{Glossary("IPv6")}} URI syntax. An RFC3986-compliant `encodeURI` implementation should not escape them, which is demonstrated in the [`encodeURI()` example](/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI#encoding_for_rfc3986). ```js function encodeRFC3986URIComponent(str) { return encodeURIComponent(str).replace( /[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, ); } ``` ### Encoding a lone surrogate throws A {{jsxref("URIError")}} will be thrown if one attempts to encode a surrogate which is not part of a high-low pair. For example: ```js // High-low pair OK encodeURIComponent("\uD800\uDFFF"); // "%F0%90%8F%BF" // Lone high-surrogate code unit throws "URIError: malformed URI sequence" encodeURIComponent("\uD800"); // Lone high-surrogate code unit throws "URIError: malformed URI sequence" encodeURIComponent("\uDFFF"); ``` You can use {{jsxref("String.prototype.toWellFormed()")}}, which replaces lone surrogates with the Unicode replacement character (U+FFFD), to avoid this error. You can also use {{jsxref("String.prototype.isWellFormed()")}} to check if a string contains lone surrogates before passing it to `encodeURIComponent()`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("decodeURI()")}} - {{jsxref("encodeURI()")}} - {{jsxref("decodeURIComponent()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/generator/index.md
--- title: Generator slug: Web/JavaScript/Reference/Global_Objects/Generator page-type: javascript-class browser-compat: javascript.builtins.Generator --- {{JSRef}} The **`Generator`** object is returned by a {{jsxref("Statements/function*", "generator function", "", 1)}} and it conforms to both the [iterable protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) and the [iterator protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol). `Generator` is a subclass of the hidden {{jsxref("Iterator")}} class. {{EmbedInteractiveExample("pages/js/expressions-functionasteriskexpression.html", "taller")}} ## Constructor The `Generator` constructor is not available globally. Instances of `Generator` must be returned from [generator functions](/en-US/docs/Web/JavaScript/Reference/Statements/function*): ```js function* generator() { yield 1; yield 2; yield 3; } const gen = generator(); // "Generator { }" console.log(gen.next().value); // 1 console.log(gen.next().value); // 2 console.log(gen.next().value); // 3 ``` In fact, there's no JavaScript entity that corresponds to the `Generator` constructor. There's only a hidden object which is the prototype object shared by all objects created by generator functions. This object is often stylized as `Generator.prototype` to make it look like a class, but it should be more appropriately called [`GeneratorFunction.prototype.prototype`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/GeneratorFunction), because `GeneratorFunction` is an actual JavaScript entity. ## Instance properties These properties are defined on `Generator.prototype` and shared by all `Generator` instances. - {{jsxref("Object/constructor", "Generator.prototype.constructor")}} - : The constructor function that created the instance object. For `Generator` instances, the initial value is [`GeneratorFunction.prototype`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/GeneratorFunction). > **Note:** `Generator` objects do not store a reference to the generator function that created them. - `Generator.prototype[@@toStringTag]` - : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"Generator"`. This property is used in {{jsxref("Object.prototype.toString()")}}. ## Instance methods _Also inherits instance methods from its parent {{jsxref("Iterator")}}_. - {{jsxref("Generator.prototype.next()")}} - : Returns a value yielded by the {{jsxref("Operators/yield", "yield")}} expression. - {{jsxref("Generator.prototype.return()")}} - : Acts as if a `return` statement is inserted in the generator's body at the current suspended position, which finishes the generator and allows the generator to perform any cleanup tasks when combined with a [`try...finally`](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch#the_finally_block) block. - {{jsxref("Generator.prototype.throw()")}} - : Acts as if a `throw` statement is inserted in the generator's body at the current suspended position, which informs the generator of an error condition and allows it to handle the error, or perform cleanup and close itself. ## Examples ### An infinite iterator With a generator function, values are not evaluated until they are needed. Therefore a generator allows us to define a potentially infinite data structure. ```js function* infinite() { let index = 0; while (true) { yield index++; } } const generator = infinite(); // "Generator { }" console.log(generator.next().value); // 0 console.log(generator.next().value); // 1 console.log(generator.next().value); // 2 // … ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Statements/function*", "function*")}} - [`function*` expression](/en-US/docs/Web/JavaScript/Reference/Operators/function*) - {{jsxref("GeneratorFunction")}} - [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/generator
data/mdn-content/files/en-us/web/javascript/reference/global_objects/generator/return/index.md
--- title: Generator.prototype.return() slug: Web/JavaScript/Reference/Global_Objects/Generator/return page-type: javascript-instance-method browser-compat: javascript.builtins.Generator.return --- {{JSRef}} The **`return()`** method of {{jsxref("Generator")}} instances acts as if a `return` statement is inserted in the generator's body at the current suspended position, which finishes the generator and allows the generator to perform any cleanup tasks when combined with a [`try...finally`](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch#the_finally_block) block. ## Syntax <!-- We don't usually add the "generatorInstance" subject for methods. However, it is necessary here, because "return" is a keyword, so otherwise it's invalid syntax. --> ```js-nolint generatorInstance.return() generatorInstance.return(value) ``` ### Parameters - `value` {{optional_inline}} - : The value to return. ### Return value An {{jsxref("Object")}} with two properties: - `done` - : A boolean value: - `true` if the generator function's control flow has reached the end. - `false` if the generator function's control flow hasn't reached the end and can produce more values. This can only happen if the `return` is captured in a [`try...finally`](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch#the_finally_block) and there are more `yield` expressions in the `finally` block. - `value` - : The value that is given as an argument, or, if the `yield` expression is wrapped in a [`try...finally`](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch#the_finally_block), the value yielded/returned from the `finally` block. ## Description The `return()` method, when called, can be seen as if a `return value;` statement is inserted in the generator's body at the current suspended position, where `value` is the value passed to the `return()` method. Therefore, in a typical flow, calling `return(value)` will return `{ done: true, value: value }`. However, if the `yield` expression is wrapped in a `try...finally` block, the control flow doesn't exit the function body, but proceeds to the `finally` block instead. In this case, the value returned may be different, and `done` may even be `false`, if there are more `yield` expressions within the `finally` block. ## Examples ### Using return() The following example shows a simple generator and the `return` method. ```js function* gen() { yield 1; yield 2; yield 3; } const g = gen(); g.next(); // { value: 1, done: false } g.return("foo"); // { value: "foo", done: true } g.next(); // { value: undefined, done: true } ``` If `return(value)` is called on a generator that is already in "completed" state, the generator will remain in "completed" state. If no argument is provided, the `value` property of the returned object will be `undefined`. If an argument is provided, it will become the value of the `value` property of the returned object, unless the `yield` expression is wrapped in a `try...finally`. ```js function* gen() { yield 1; yield 2; yield 3; } const g = gen(); g.next(); // { value: 1, done: false } g.next(); // { value: 2, done: false } g.next(); // { value: 3, done: false } g.next(); // { value: undefined, done: true } g.return(); // { value: undefined, done: true } g.return(1); // { value: 1, done: true } ``` ### Using return() with try...finally The fact that the `return` method has been called can only be made known to the generator itself if the `yield` expression is wrapped in a `try...finally` block. When the `return` method is called on a generator that is suspended within a `try` block, execution in the generator proceeds to the `finally` block — since the `finally` block of `try...finally` statements always executes. ```js function* gen() { yield 1; try { yield 2; yield 3; } finally { yield "cleanup"; } } const g1 = gen(); g1.next(); // { value: 1, done: false } // Execution is suspended before the try...finally. g1.return("early return"); // { value: 'early return', done: true } const g2 = gen(); g2.next(); // { value: 1, done: false } g2.next(); // { value: 2, done: false } // Execution is suspended within the try...finally. g2.return("early return"); // { value: 'cleanup', done: false } // The completion value is preserved g2.next(); // { value: 'early return', done: true } // Generator is in the completed state g2.return("not so early return"); // { value: 'not so early return', done: true } ``` The return value of the finally block can also become the `value` of the result returned from the `return` call. ```js function* gen() { try { yield 1; } finally { return "cleanup"; } } const g1 = gen(); g1.next(); // { value: 1, done: false } g1.return("early return"); // { value: 'cleanup', done: true } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Statements/function*", "function*")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/generator
data/mdn-content/files/en-us/web/javascript/reference/global_objects/generator/throw/index.md
--- title: Generator.prototype.throw() slug: Web/JavaScript/Reference/Global_Objects/Generator/throw page-type: javascript-instance-method browser-compat: javascript.builtins.Generator.throw --- {{JSRef}} The **`throw()`** method of {{jsxref("Generator")}} instances acts as if a `throw` statement is inserted in the generator's body at the current suspended position, which informs the generator of an error condition and allows it to handle the error, or perform cleanup and close itself. ## Syntax <!-- We don't usually add the "generatorInstance" subject for methods. However, it is necessary here, because "throw" is a keyword, so otherwise it's invalid syntax. --> ```js-nolint generatorInstance.throw(exception) ``` ### Parameters - `exception` - : The exception to throw. For debugging purposes, it is useful to make it an `instanceof` {{jsxref("Error")}}. ### Return value If the thrown exception is caught by a [`try...catch`](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch) and the generator resumes to yield more values, it will return an {{jsxref("Object")}} with two properties: - `done` - : A boolean value: - `true` if the generator function's control flow has reached the end. - `false` if the generator function is able to produce more values. - `value` - : The value yielded from the next `yield` expression. ### Exceptions If the thrown exception is not caught by a `try...catch`, the `exception` passed to `throw()` will be thrown out from the generator function. ## Description The `throw()` method, when called, can be seen as if a `throw exception;` statement is inserted in the generator's body at the current suspended position, where `exception` is the exception passed to the `throw()` method. Therefore, in a typical flow, calling `throw(exception)` will cause the generator to throw. However, if the `yield` expression is wrapped in a `try...catch` block, the error may be caught and control flow can either resume after error handling, or exit gracefully. ## Examples ### Using throw() The following example shows a simple generator and an error that is thrown using the `throw` method. An error can be caught by a {{jsxref("Statements/try...catch", "try...catch")}} block as usual. ```js function* gen() { while (true) { try { yield 42; } catch (e) { console.log("Error caught!"); } } } const g = gen(); g.next(); // { value: 42, done: false } g.throw(new Error("Something went wrong")); // "Error caught!" // { value: 42, done: false } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Statements/function*", "function*")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/generator
data/mdn-content/files/en-us/web/javascript/reference/global_objects/generator/next/index.md
--- title: Generator.prototype.next() slug: Web/JavaScript/Reference/Global_Objects/Generator/next page-type: javascript-instance-method browser-compat: javascript.builtins.Generator.next --- {{JSRef}} The **`next()`** method of {{jsxref("Generator")}} instances returns an object with two properties `done` and `value`. You can also provide a parameter to the `next` method to send a value to the generator. ## Syntax ```js-nolint next() next(value) ``` ### Parameters - `value` {{optional_inline}} - : The value to send to the generator. The value will be assigned as a result of a `yield` expression. For example, in `variable = yield expression`, the value passed to the `.next()` function will be assigned to `variable`. ### Return value An {{jsxref("Object")}} with two properties: - `done` - : A boolean value: - `true` if the generator is past the end of its control flow. In this case `value` specifies the _return value_ of the generator (which may be undefined). - `false` if the generator is able to produce more values. - `value` - : Any JavaScript value yielded or returned by the generator. ## Examples ### Using next() The following example shows a simple generator and the object that the `next` method returns: ```js function* gen() { yield 1; yield 2; yield 3; } const g = gen(); // Generator { } g.next(); // { value: 1, done: false } g.next(); // { value: 2, done: false } g.next(); // { value: 3, done: false } g.next(); // { value: undefined, done: true } ``` ### Using next() with a list In this example, `getPage` takes a list and "paginates" it into chunks of size `pageSize`. Each call to `next` will yield one such chunk. ```js function* getPage(list, pageSize = 1) { for (let index = 0; index < list.length; index += pageSize) { yield list.slice(index, index + pageSize); } } const list = [1, 2, 3, 4, 5, 6, 7, 8]; const page = getPage(list, 3); // Generator { } page.next(); // { value: [1, 2, 3], done: false } page.next(); // { value: [4, 5, 6], done: false } page.next(); // { value: [7, 8], done: false } page.next(); // { value: undefined, done: true } ``` ### Sending values to the generator In this example, `next` is called with a value. > **Note:** The first call does not log anything, because the generator was not yielding anything initially. ```js function* gen() { while (true) { const value = yield; console.log(value); } } const g = gen(); g.next(1); // Returns { value: undefined, done: false } // No log at this step: the first value sent through `next` is lost g.next(2); // Returns { value: undefined, done: false } // Logs 2 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Statements/function*", "function*")}} - [Iterators and generators](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators) guide
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/finalizationregistry/index.md
--- title: FinalizationRegistry slug: Web/JavaScript/Reference/Global_Objects/FinalizationRegistry page-type: javascript-class browser-compat: javascript.builtins.FinalizationRegistry --- {{JSRef}} A **`FinalizationRegistry`** object lets you request a callback when a value is garbage-collected. ## Description `FinalizationRegistry` provides a way to request that a _cleanup callback_ get called at some point when a value registered with the registry has been _reclaimed_ (garbage-collected). (Cleanup callbacks are sometimes called _finalizers_.) > **Note:** Cleanup callbacks should not be used for essential program logic. See [Notes on cleanup callbacks](#notes_on_cleanup_callbacks) for details. You create the registry passing in the callback: ```js const registry = new FinalizationRegistry((heldValue) => { // … }); ``` Then you register any value you want a cleanup callback for by calling the `register` method, passing in the value and a _held value_ for it: ```js registry.register(target, "some value"); ``` The registry does not keep a strong reference to the value, as that would defeat the purpose (if the registry held it strongly, the value would never be reclaimed). In JavaScript, objects and [non-registered symbols](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) are garbage collectable, so they can be registered in a `FinalizationRegistry` object as the target or the token. If `target` is reclaimed, your cleanup callback may be called at some point with the _held value_ you provided for it (`"some value"` in the above). The held value can be any value you like: a primitive or an object, even `undefined`. If the held value is an object, the registry keeps a _strong_ reference to it (so it can pass it to your cleanup callback later). If you might want to unregister a registered target value later, you pass a third value, which is the _unregistration token_ you'll use later when calling the registry's `unregister` function to unregister the value. The registry only keeps a weak reference to the unregister token. It's common to use the target value itself as the unregister token, which is just fine: ```js registry.register(target, "some value", target); // … // some time later, if you don't care about `target` anymore, unregister it registry.unregister(target); ``` It doesn't have to be the same value, though; it can be a different one: ```js registry.register(target, "some value", token); // … // some time later registry.unregister(token); ``` ### Avoid where possible Correct use of `FinalizationRegistry` takes careful thought, and it's best avoided if possible. It's also important to avoid relying on any specific behaviors not guaranteed by the specification. When, how, and whether garbage collection occurs is down to the implementation of any given JavaScript engine. Any behavior you observe in one engine may be different in another engine, in another version of the same engine, or even in a slightly different situation with the same version of the same engine. Garbage collection is a hard problem that JavaScript engine implementers are constantly refining and improving their solutions to. Here are some specific points included by the authors in the [proposal](https://github.com/tc39/proposal-weakrefs) that introduced `FinalizationRegistry`: > [Garbage collectors](<https://en.wikipedia.org/wiki/Garbage_collection_(computer_science)>) are complicated. If an application or library depends on GC cleaning up a WeakRef or calling a finalizer \[cleanup callback] in a timely, predictable manner, it's likely to be disappointed: the cleanup may happen much later than expected, or not at all. Sources of variability include: > > - One object might be garbage-collected much sooner than another object, even if they become unreachable at the same time, e.g., due to generational collection. > - Garbage collection work can be split up over time using incremental and concurrent techniques. > - Various runtime heuristics can be used to balance memory usage, responsiveness. > - The JavaScript engine may hold references to things which look like they are unreachable (e.g., in closures, or inline caches). > - Different JavaScript engines may do these things differently, or the same engine may change its algorithms across versions. > - Complex factors may lead to objects being held alive for unexpected amounts of time, such as use with certain APIs. ### Notes on cleanup callbacks - Developers shouldn't rely on cleanup callbacks for essential program logic. Cleanup callbacks may be useful for reducing memory usage across the course of a program, but are unlikely to be useful otherwise. - If your code has just registered a value to the registry, that target will not be reclaimed until the end of the current JavaScript [job](https://tc39.es/ecma262/multipage/executable-code-and-execution-contexts.html#job). See [notes on WeakRefs](/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef#notes_on_weakrefs) for details. - A conforming JavaScript implementation, even one that does garbage collection, is not required to call cleanup callbacks. When and whether it does so is entirely down to the implementation of the JavaScript engine. When a registered object is reclaimed, any cleanup callbacks for it may be called then, or some time later, or not at all. - It's likely that major implementations will call cleanup callbacks at some point during execution, but those calls may be substantially after the related object was reclaimed. Furthermore, if there is an object registered in two registries, there is no guarantee that the two callbacks are called next to each other — one may be called and the other never called, or the other may be called much later. - There are also situations where even implementations that normally call cleanup callbacks are unlikely to call them: - When the JavaScript program shuts down entirely (for instance, closing a tab in a browser). - When the `FinalizationRegistry` instance itself is no longer reachable by JavaScript code. - If the target of a `WeakRef` is also in a `FinalizationRegistry`, the `WeakRef`'s target is cleared at the same time or before any cleanup callback associated with the registry is called; if your cleanup callback calls `deref` on a `WeakRef` for the object, it will receive `undefined`. ## Constructor - {{jsxref("FinalizationRegistry/FinalizationRegistry", "FinalizationRegistry()")}} - : Creates a new `FinalizationRegistry` object. ## Instance properties These properties are defined on `FinalizationRegistry.prototype` and shared by all `FinalizationRegistry` instances. - {{jsxref("Object/constructor", "FinalizationRegistry.prototype.constructor")}} - : The constructor function that created the instance object. For `FinalizationRegistry` instances, the initial value is the {{jsxref("FinalizationRegistry/FinalizationRegistry", "FinalizationRegistry")}} constructor. - `FinalizationRegistry.prototype[@@toStringTag]` - : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"FinalizationRegistry"`. This property is used in {{jsxref("Object.prototype.toString()")}}. ## Instance methods - {{jsxref("FinalizationRegistry.prototype.register()")}} - : Registers an object with the registry in order to get a cleanup callback when/if the object is garbage-collected. - {{jsxref("FinalizationRegistry.prototype.unregister()")}} - : Unregisters an object from the registry. ## Examples ### Creating a new registry You create the registry passing in the callback: ```js const registry = new FinalizationRegistry((heldValue) => { // … }); ``` ### Registering objects for cleanup Then you register any objects you want a cleanup callback for by calling the `register` method, passing in the object and a _held value_ for it: ```js registry.register(theObject, "some value"); ``` ### Callbacks never called synchronously No matter how much pressure you put on the garbage collector, the cleanup callback will never be called synchronously. The object may be reclaimed synchronously, but the callback will always be called sometime after the current job finishes: ```js let counter = 0; const registry = new FinalizationRegistry(() => { console.log(`Array gets garbage collected at ${counter}`); }); registry.register(["foo"]); (function allocateMemory() { // Allocate 50000 functions — a lot of memory! Array.from({ length: 50000 }, () => () => {}); if (counter > 5000) return; counter++; allocateMemory(); })(); console.log("Main job ends"); // Logs: // Main job ends // Array gets garbage collected at 5001 ``` However, if you allow a little break between each allocation, the callback may be called sooner: ```js let arrayCollected = false; let counter = 0; const registry = new FinalizationRegistry(() => { console.log(`Array gets garbage collected at ${counter}`); arrayCollected = true; }); registry.register(["foo"]); (function allocateMemory() { // Allocate 50000 functions — a lot of memory! Array.from({ length: 50000 }, () => () => {}); if (counter > 5000 || arrayCollected) return; counter++; // Use setTimeout to make each allocateMemory a different job setTimeout(allocateMemory); })(); console.log("Main job ends"); ``` There's no guarantee that the callback will be called sooner or if it will be called at all, but there's a possibility that the logged message has a counter value smaller than 5000. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("WeakRef")}} - {{jsxref("WeakSet")}} - {{jsxref("WeakMap")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/finalizationregistry
data/mdn-content/files/en-us/web/javascript/reference/global_objects/finalizationregistry/register/index.md
--- title: FinalizationRegistry.prototype.register() slug: Web/JavaScript/Reference/Global_Objects/FinalizationRegistry/register page-type: javascript-instance-method browser-compat: javascript.builtins.FinalizationRegistry.register --- {{JSRef}} The **`register()`** method of {{jsxref("FinalizationRegistry")}} instances registers an value with this `FinalizationRegistry` so that if the value is garbage-collected, the registry's callback may get called. ## Syntax ```js-nolint register(target, heldValue) register(target, heldValue, unregisterToken) ``` ### Parameters - `target` - : The target value to register. - `heldValue` - : The value to pass to the finalizer for this `target`. This cannot be the `target` itself but can be anything else, including functions and primitives. - `unregisterToken` {{optional_inline}} - : A token that may be used with the `unregister` method later to unregister the target value. If provided (and not `undefined`), this must be an object or a [non-registered symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry). If not provided, the target cannot be unregistered. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - {{jsxref("TypeError")}} - : Thrown in one of the following cases: - `target` is not an object or a [non-registered symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) (object as opposed to primitives; functions are objects as well) - `target` is the same as `heldvalue` (`target === heldValue`) - `unregisterToken` is not an object or a [non-registered symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) ## Description See the [Avoid where possible](/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#avoid_where_possible) and [Notes on cleanup callbacks](/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#notes_on_cleanup_callbacks) sections of the {{jsxref("FinalizationRegistry")}} page for important caveats. ## Examples ### Using register The following registers the value referenced by `target`, passing in the held value `"some value"` and passing the target itself as the unregistration token: ```js registry.register(target, "some value", target); ``` The following registers the value referenced by `target`, passing in another object as the held value, and not passing in any unregistration token (which means `target` can't be unregistered): ```js registry.register(target, { useful: "info about target" }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("FinalizationRegistry")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/finalizationregistry
data/mdn-content/files/en-us/web/javascript/reference/global_objects/finalizationregistry/unregister/index.md
--- title: FinalizationRegistry.prototype.unregister() slug: Web/JavaScript/Reference/Global_Objects/FinalizationRegistry/unregister page-type: javascript-instance-method browser-compat: javascript.builtins.FinalizationRegistry.unregister --- {{JSRef}} The **`unregister()`** method of {{jsxref("FinalizationRegistry")}} instances unregisters a target value from this `FinalizationRegistry`. ## Syntax ```js-nolint unregister(unregisterToken) ``` ### Parameters - `unregisterToken` - : The token used with the {{jsxref("FinalizationRegistry/register", "register()")}} method when registering the target value. Multiple cells registered with the same `unregisterToken` will be unregistered together. ### Return value A boolean value that is `true` if at least one cell was unregistered and `false` if no cell was unregistered. ### Exceptions - {{jsxref("TypeError")}} - : Thrown if `unregisterToken` is not an object or a [non-registered symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry). ## Description When a target value has been reclaimed, it is no longer registered in the registry. There is no need to call `unregister` in your cleanup callback. Only call `unregister` if you haven't received a cleanup callback and no longer need to receive one. ## Examples ### Using unregister This example shows registering a target object using that same object as the unregister token, then later unregistering it via `unregister`: ```js class Thingy { static #cleanup = (label) => { // ^^^^^−−−−− held value console.error( `The "release" method was never called for the object with the label "${label}"`, ); }; #registry = new FinalizationRegistry(Thingy.#cleanup); /** * Constructs a `Thingy` instance. * Be sure to call `release` when you're done with it. * * @param label A label for the `Thingy`. */ constructor(label) { // vvvvv−−−−− held value this.#registry.register(this, label, this); // target −−−−−^^^^ ^^^^−−−−− unregister token } /** * Releases resources held by this `Thingy` instance. */ release() { this.#registry.unregister(this); // ^^^^−−−−− unregister token } } ``` This example shows registering a target object using a different object as its unregister token: ```js class Thingy { static #cleanup = (file) => { // ^^^^−−−−− held value console.error( `The "release" method was never called for the "Thingy" for the file "${file.name}"`, ); }; #registry = new FinalizationRegistry(Thingy.#cleanup); #file; /** * Constructs a `Thingy` instance for the given file. * Be sure to call `release` when you're done with it. * * @param filename The name of the file. */ constructor(filename) { this.#file = File.open(filename); // vvvvv−−−−− held value this.#registry.register(this, label, this.#file); // target −−−−−^^^^ ^^^^^^^^^^−−−−− unregister token } /** * Releases resources held by this `Thingy` instance. */ release() { if (this.#file) { this.#registry.unregister(this.#file); // ^^^^^^^^^^−−−−− unregister token File.close(this.#file); this.#file = null; } } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("FinalizationRegistry")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/finalizationregistry
data/mdn-content/files/en-us/web/javascript/reference/global_objects/finalizationregistry/finalizationregistry/index.md
--- title: FinalizationRegistry() constructor slug: Web/JavaScript/Reference/Global_Objects/FinalizationRegistry/FinalizationRegistry page-type: javascript-constructor browser-compat: javascript.builtins.FinalizationRegistry.FinalizationRegistry --- {{JSRef}} The **`FinalizationRegistry()`** constructor creates {{jsxref("FinalizationRegistry")}} objects. ## Syntax ```js-nolint new FinalizationRegistry(callbackFn) ``` > **Note:** `FinalizationRegistry()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}. ### Parameters - `callback` - : A function to be invoked each time a registered target value is garbage collected. Its return value is ignored. The function is called with the following arguments: - `heldValue` - : The value that was passed to the second parameter of the {{jsxref("FinalizationRegistry/register", "register()")}} method when the `target` object was registered. ## Examples ### Creating a new registry You create the registry passing in the callback: ```js const registry = new FinalizationRegistry((heldValue) => { // … }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("FinalizationRegistry")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/parseint/index.md
--- title: parseInt() slug: Web/JavaScript/Reference/Global_Objects/parseInt page-type: javascript-function browser-compat: javascript.builtins.parseInt --- {{jsSidebar("Objects")}} The **`parseInt()`** function parses a string argument and returns an integer of the specified [radix](https://en.wikipedia.org/wiki/Radix) (the base in mathematical numeral systems). {{EmbedInteractiveExample("pages/js/globalprops-parseint.html")}} ## Syntax ```js-nolint parseInt(string) parseInt(string, radix) ``` ### Parameters - `string` - : A string starting with an integer. Leading {{Glossary("whitespace")}} in this argument is ignored. - `radix` {{optional_inline}} - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. It is converted to a [32-bit integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#fixed-width_number_conversion); if it's nonzero and outside the range of \[2, 36] after conversion, the function will always return `NaN`. If `0` or not provided, the radix will be inferred based on `string`'s value. Be careful — this does _not_ always default to `10`! The [description below](#description) explains in more detail what happens when `radix` is not provided. ### Return value An integer parsed from the given `string`, or {{jsxref("NaN")}} when - the `radix` as a 32-bit integer is smaller than `2` or bigger than `36`, or - the first non-whitespace character cannot be converted to a number. > **Note:** JavaScript does not have the distinction of "floating point numbers" and "integers" on the language level. `parseInt()` and [`parseFloat()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat) only differ in their parsing behavior, but not necessarily their return values. For example, `parseInt("42")` and `parseFloat("42")` would return the same value: a {{jsxref("Number")}} 42. ## Description The `parseInt` function [converts its first argument to a string](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion), parses that string, then returns an integer or `NaN`. If not `NaN`, the return value will be the integer that is the first argument taken as a number in the specified `radix`. (For example, a `radix` of `10` converts from a decimal number, `8` converts from octal, `16` from hexadecimal, and so on.) The `radix` argument is [converted to a number](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion). If it's unprovided, or if the value becomes 0, `NaN` or `Infinity` (`undefined` is coerced to `NaN`), JavaScript assumes the following: 1. If the input `string`, with leading whitespace and possible `+`/`-` signs removed, begins with `0x` or `0X` (a zero, followed by lowercase or uppercase X), `radix` is assumed to be `16` and the rest of the string is parsed as a hexadecimal number. 2. If the input `string` begins with any other value, the radix is `10` (decimal). > **Note:** Other prefixes like `0b`, which are valid in [number literals](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#binary), are treated as normal digits by `parseInt()`. `parseInt()` does _not_ treat strings beginning with a `0` character as octal values either. The only prefix that `parseInt()` recognizes is `0x` or `0X` for hexadecimal values — everything else is parsed as a decimal value if `radix` is missing. [`Number()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/Number) or [`BigInt()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/BigInt) can be used instead to parse these prefixes. If the radix is `16`, `parseInt()` allows the string to be optionally prefixed by `0x` or `0X` after the optional sign character (`+`/`-`). If the radix value (coerced if necessary) is not in range \[2, 36] (inclusive) `parseInt` returns `NaN`. For radices above `10`, letters of the English alphabet indicate numerals greater than `9`. For example, for hexadecimal numbers (base `16`), `A` through `F` are used. The letters are case-insensitive. `parseInt` understands exactly two signs: `+` for positive, and `-` for negative. It is done as an initial step in the parsing after whitespace is removed. If no signs are found, the algorithm moves to the following step; otherwise, it removes the sign and runs the number-parsing on the rest of the string. If `parseInt` encounters a character that is not a numeral in the specified `radix`, it ignores it and all succeeding characters and returns the integer value parsed up to that point. For example, although `1e3` technically encodes an integer (and will be correctly parsed to the integer `1000` by [`parseFloat()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat)), `parseInt("1e3", 10)` returns `1`, because `e` is not a valid numeral in base 10. Because `.` is not a numeral either, the return value will always be an integer. If the first character cannot be converted to a number with the radix in use, `parseInt` returns `NaN`. Leading whitespace is allowed. For arithmetic purposes, the `NaN` value is not a number in any radix. You can call the [`Number.isNaN`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN) function to determine if the result of `parseInt` is `NaN`. If `NaN` is passed on to arithmetic operations, the operation result will also be `NaN`. Because large numbers use the `e` character in their string representation (e.g. `6.022e23` for 6.022 × 10<sup>23</sup>), using `parseInt` to truncate numbers will produce unexpected results when used on very large or very small numbers. `parseInt` should _not_ be used as a substitute for {{jsxref("Math.trunc()")}}. To convert a number to its string literal in a particular radix, use [`thatNumber.toString(radix)`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString). Because `parseInt()` returns a number, it may suffer from loss of precision if the integer represented by the string is [outside the safe range](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). The [`BigInt()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/BigInt) function supports parsing integers of arbitrary length accurately, by returning a {{jsxref("BigInt")}}. ## Examples ### Using parseInt() The following examples all return `15`: ```js parseInt("0xF", 16); parseInt("F", 16); parseInt("17", 8); parseInt("015", 10); // but `parseInt('015', 8)` will return 13 parseInt("15,123", 10); parseInt("FXX123", 16); parseInt("1111", 2); parseInt("15 * 3", 10); parseInt("15e2", 10); parseInt("15px", 10); parseInt("12", 13); ``` The following examples all return `NaN`: ```js parseInt("Hello", 8); // Not a number at all parseInt("546", 2); // Digits other than 0 or 1 are invalid for binary radix ``` The following examples all return `-15`: ```js parseInt("-F", 16); parseInt("-0F", 16); parseInt("-0XF", 16); parseInt("-17", 8); parseInt("-15", 10); parseInt("-1111", 2); parseInt("-15e1", 10); parseInt("-12", 13); ``` The following example returns `224`: ```js parseInt("0e0", 16); ``` `parseInt()` does not handle {{jsxref("BigInt")}} values. It stops at the `n` character, and treats the preceding string as a normal integer, with possible loss of precision. ```js example-bad parseInt("900719925474099267n"); // 900719925474099300 ``` You should pass the string to the [`BigInt()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/BigInt) function instead, without the trailing `n` character. ```js example-good BigInt("900719925474099267"); // 900719925474099267n ``` `parseInt` doesn't work with [numeric separators](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#numeric_separators): ```js example-bad parseInt("123_456"); // 123 ``` ### Using parseInt() on non-strings `parseInt()` can have interesting results when working on non-strings combined with a high radix; for example, `36` (which makes all alphanumeric characters valid numeric digits). ```js parseInt(null, 36); // 1112745: The string "null" is 1112745 in base 36 parseInt(undefined, 36); // 86464843759093: The string "undefined" is 86464843759093 in base 36 ``` In general, it's a bad idea to use `parseInt()` on non-strings, especially to use it as a substitution for {{jsxref("Math.trunc()")}}. It may work on small numbers: ```js parseInt(15.99, 10); // 15 parseInt(-15.1, 10); // -15 ``` However, it only happens to work because the string representation of these numbers uses basic fractional notation (`"15.99"`, `"-15.1"`), where `parseInt()` stops at the decimal point. Numbers greater than or equal to 1e+21 or less than or equal to 1e-7 use exponential notation (`"1.5e+22"`, `"1.51e-8"`) in their string representation, and `parseInt()` will stop at the `e` character or decimal point, which always comes after the first digit. This means for large and small numbers, `parseInt()` will return a one-digit integer: ```js example-bad parseInt(4.7 * 1e22, 10); // Very large number becomes 4 parseInt(0.00000000000434, 10); // Very small number becomes 4 parseInt(0.0000001, 10); // 1 parseInt(0.000000123, 10); // 1 parseInt(1e-7, 10); // 1 parseInt(1000000000000000000000, 10); // 1 parseInt(123000000000000000000000, 10); // 1 parseInt(1e21, 10); // 1 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("parseFloat()")}} - [`Number()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/Number) - {{jsxref("Number.parseFloat()")}} - {{jsxref("Number.parseInt()")}} - {{jsxref("isNaN()")}} - {{jsxref("Number.prototype.toString()")}} - {{jsxref("Object.prototype.valueOf()")}} - [`BigInt()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/BigInt)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakmap/index.md
--- title: WeakMap slug: Web/JavaScript/Reference/Global_Objects/WeakMap page-type: javascript-class browser-compat: javascript.builtins.WeakMap --- {{JSRef}} A **`WeakMap`** is a collection of key/value pairs whose keys must be objects or [non-registered symbols](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry), with values of any arbitrary [JavaScript type](/en-US/docs/Web/JavaScript/Data_structures), and which does not create strong references to its keys. That is, an object's presence as a key in a `WeakMap` does not prevent the object from being garbage collected. Once an object used as a key has been collected, its corresponding values in any `WeakMap` become candidates for garbage collection as well — as long as they aren't strongly referred to elsewhere. The only primitive type that can be used as a `WeakMap` key is symbol — more specifically, [non-registered symbols](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) — because non-registered symbols are guaranteed to be unique and cannot be re-created. `WeakMap` allows associating data to objects in a way that doesn't prevent the key objects from being collected, even if the values reference the keys. However, a `WeakMap` doesn't allow observing the liveness of its keys, which is why it doesn't allow enumeration; if a `WeakMap` exposed any method to obtain a list of its keys, the list would depend on the state of garbage collection, introducing non-determinism. If you want to have a list of keys, you should use a {{jsxref("Map")}} rather than a `WeakMap`. You can learn more about `WeakMap` in the [WeakMap object](/en-US/docs/Web/JavaScript/Guide/Keyed_collections#weakmap_object) section of the [Keyed collections](/en-US/docs/Web/JavaScript/Guide/Keyed_collections) guide. ## Description Keys of WeakMaps must be garbage-collectable. Most {{Glossary("Primitive", "primitive data types")}} can be arbitrarily created and don't have a lifetime, so they cannot be used as keys. Objects and [non-registered symbols](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) can be used as keys because they are garbage-collectable. ### Why WeakMap? A map API _could_ be implemented in JavaScript with two arrays (one for keys, one for values) shared by the four API methods. Setting elements on this map would involve pushing a key and value onto the end of each of those arrays simultaneously. As a result, the indices of the key and value would correspond to both arrays. Getting values from the map would involve iterating through all keys to find a match, then using the index of this match to retrieve the corresponding value from the array of values. Such an implementation would have two main inconveniences: 1. The first one is an `O(n)` set and search (_n_ being the number of keys in the map) since both operations must iterate through the list of keys to find a matching value. 2. The second inconvenience is a memory leak because the arrays ensure that references to each key and each value are maintained indefinitely. These references prevent the keys from being garbage collected, even if there are no other references to the object. This would also prevent the corresponding values from being garbage collected. By contrast, in a `WeakMap`, a key object refers strongly to its contents as long as the key is not garbage collected, but weakly from then on. As such, a `WeakMap`: - does not prevent garbage collection, which eventually removes references to the key object - allows garbage collection of any values if their key objects are not referenced from somewhere other than a `WeakMap` A `WeakMap` can be a particularly useful construct when mapping keys to information about the key that is valuable _only if_ the key has not been garbage collected. But because a `WeakMap` doesn't allow observing the liveness of its keys, its keys are not enumerable. There is no method to obtain a list of the keys. If there were, the list would depend on the state of garbage collection, introducing non-determinism. If you want to have a list of keys, you should use a {{jsxref("Map")}}. ## Constructor - {{jsxref("WeakMap/WeakMap", "WeakMap()")}} - : Creates a new `WeakMap` object. ## Instance properties These properties are defined on `WeakMap.prototype` and shared by all `WeakMap` instances. - {{jsxref("Object/constructor", "WeakMap.prototype.constructor")}} - : The constructor function that created the instance object. For `WeakMap` instances, the initial value is the {{jsxref("WeakMap/WeakMap", "WeakMap")}} constructor. - `WeakMap.prototype[@@toStringTag]` - : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"WeakMap"`. This property is used in {{jsxref("Object.prototype.toString()")}}. ## Instance methods - {{jsxref("WeakMap.prototype.delete()")}} - : Removes any value associated to the `key`. `WeakMap.prototype.has(key)` will return `false` afterwards. - {{jsxref("WeakMap.prototype.get()")}} - : Returns the value associated to the `key`, or `undefined` if there is none. - {{jsxref("WeakMap.prototype.has()")}} - : Returns a Boolean asserting whether a value has been associated to the `key` in the `WeakMap` object or not. - {{jsxref("WeakMap.prototype.set()")}} - : Sets the `value` for the `key` in the `WeakMap` object. Returns the `WeakMap` object. ## 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(o2, undefined); wm2.set(wm1, wm2); // keys and values can be any objects. Even WeakMaps! wm1.get(o2); // "azerty" wm2.get(o2); // undefined, because that is the set value wm2.get(o3); // undefined, because there is no key for o3 on wm2 wm1.has(o2); // true wm2.has(o2); // true (even if the value itself is 'undefined') wm2.has(o3); // false wm3.set(o1, 37); wm3.get(o1); // 37 wm1.has(o1); // true wm1.delete(o1); wm1.has(o1); // false ``` ### Implementing a WeakMap-like class with a .clear() method ```js class ClearableWeakMap { #wm; constructor(init) { this.#wm = new WeakMap(init); } clear() { this.#wm = new WeakMap(); } delete(k) { return this.#wm.delete(k); } get(k) { return this.#wm.get(k); } has(k) { return this.#wm.has(k); } set(k, v) { this.#wm.set(k, v); return this; } } ``` ### Emulating private members Developers can use a `WeakMap` to associate private data to an object, with the following benefits: - Compared to a {{jsxref("Map")}}, a WeakMap does not hold strong references to the object used as the key, so the metadata shares the same lifetime as the object itself, avoiding memory leaks. - Compared to using non-enumerable and/or {{jsxref("Symbol")}} properties, a WeakMap is external to the object and there is no way for user code to retrieve the metadata through reflective methods like {{jsxref("Object.getOwnPropertySymbols")}}. - Compared to a [closure](/en-US/docs/Web/JavaScript/Closures), the same WeakMap can be reused for all instances created from a constructor, making it more memory-efficient, and allows different instances of the same class to read the private members of each other. ```js let Thing; { const privateScope = new WeakMap(); let counter = 0; Thing = function () { this.someProperty = "foo"; privateScope.set(this, { hidden: ++counter, }); }; Thing.prototype.showPublic = function () { return this.someProperty; }; Thing.prototype.showPrivate = function () { return privateScope.get(this).hidden; }; } console.log(typeof privateScope); // "undefined" const thing = new Thing(); console.log(thing); // Thing {someProperty: "foo"} thing.showPublic(); // "foo" thing.showPrivate(); // 1 ``` This is roughly equivalent to the following, using [private fields](/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties): ```js class Thing { static #counter = 0; #hidden; constructor() { this.someProperty = "foo"; this.#hidden = ++Thing.#counter; } showPublic() { return this.someProperty; } showPrivate() { return this.#hidden; } } console.log(thing); // Thing {someProperty: "foo"} thing.showPublic(); // "foo" thing.showPrivate(); // 1 ``` ### Associating metadata A {{jsxref("WeakMap")}} can be used to associate metadata with an object, without affecting the lifetime of the object itself. This is very similar to the private members example, since private members are also modelled as external metadata that doesn't participate in [prototypical inheritance](/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain). This use case can be extended to already-created objects. For example, on the web, we may want to associate extra data with a DOM element, which the DOM element may access later. A common approach is to attach the data as a property: ```js const buttons = document.querySelectorAll(".button"); buttons.forEach((button) => { button.clicked = false; button.addEventListener("click", () => { button.clicked = true; const currentButtons = [...document.querySelectorAll(".button")]; if (currentButtons.every((button) => button.clicked)) { console.log("All buttons have been clicked!"); } }); }); ``` This approach works, but it has a few pitfalls: - The `clicked` property is enumerable, so it will show up in [`Object.keys(button)`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in) loops, etc. This can be mitigated by using {{jsxref("Object.defineProperty()")}}, but that makes the code more verbose. - The `clicked` property is a normal string property, so it can be accessed and overwritten by other code. This can be mitigated by using a {{jsxref("Symbol")}} key, but the key would still be accessible via {{jsxref("Object.getOwnPropertySymbols()")}}. Using a `WeakMap` fixes these: ```js const buttons = document.querySelectorAll(".button"); const clicked = new WeakMap(); buttons.forEach((button) => { clicked.set(button, false); button.addEventListener("click", () => { clicked.set(button, true); const currentButtons = [...document.querySelectorAll(".button")]; if (currentButtons.every((button) => clicked.get(button))) { console.log("All buttons have been clicked!"); } }); }); ``` Here, only code that has access to `clicked` knows the clicked state of each button, and external code can't modify the states. In addition, if any of the buttons gets removed from the DOM, the associated metadata will automatically get garbage-collected. ### Caching You can associate objects passed to a function with the result of the function, so that if the same object is passed again, the cached result can be returned without re-executing the function. This is useful if the function is pure (i.e. it doesn't mutate any outside objects or cause other observable side effects). ```js const cache = new WeakMap(); function handleObjectValues(obj) { if (cache.has(obj)) { return cache.get(obj); } const result = Object.values(obj).map(heavyComputation); cache.set(obj, result); return result; } ``` This only works if your function's input is an object. Moreover, even if the input is never passed in again, the result still remains forever in the cache. A more effective way is to use a {{jsxref("Map")}} paired with {{jsxref("WeakRef")}} objects, which allows you to associate any type of input value with its respective (potentially large) computation result. See the [WeakRefs and FinalizationRegistry](/en-US/docs/Web/JavaScript/Memory_management#weakrefs_and_finalizationregistry) example for more details. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `WeakMap` in `core-js`](https://github.com/zloirock/core-js#weakmap) - [Keyed collections](/en-US/docs/Web/JavaScript/Guide/Keyed_collections#weakmap_object) - [Hiding Implementation Details with ECMAScript 6 WeakMaps](https://fitzgeraldnick.com/2014/01/13/hiding-implementation-details-with-e6-weakmaps.html) by Nick Fitzgerald (2014) - {{jsxref("Map")}} - {{jsxref("Set")}} - {{jsxref("WeakSet")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakmap
data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakmap/get/index.md
--- title: WeakMap.prototype.get() slug: Web/JavaScript/Reference/Global_Objects/WeakMap/get page-type: javascript-instance-method browser-compat: javascript.builtins.WeakMap.get --- {{JSRef}} The **`get()`** method of {{jsxref("WeakMap")}} instances returns a specified element from this `WeakMap`. {{EmbedInteractiveExample("pages/js/weakmap-prototype-get.html")}} ## Syntax ```js-nolint 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, {{jsxref("undefined")}} is returned. Always returns `undefined` if `key` is not an object or a [non-registered symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry). ## Examples ### Using the get() method ```js const wm = new WeakMap(); wm.set(window, "foo"); wm.get(window); // Returns "foo". wm.get("baz"); // Returns undefined. ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("WeakMap")}} - {{jsxref("WeakMap.prototype.set()")}} - {{jsxref("WeakMap.prototype.has()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakmap
data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakmap/has/index.md
--- title: WeakMap.prototype.has() slug: Web/JavaScript/Reference/Global_Objects/WeakMap/has page-type: javascript-instance-method browser-compat: javascript.builtins.WeakMap.has --- {{JSRef}} The **`has()`** method of {{jsxref("WeakMap")}} instances returns a boolean indicating whether an element with the specified key exists in this `WeakMap` or not. {{EmbedInteractiveExample("pages/js/weakmap-prototype-has.html")}} ## Syntax ```js-nolint 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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry). ## 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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("WeakMap")}} - {{jsxref("WeakMap.prototype.set()")}} - {{jsxref("WeakMap.prototype.get()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakmap
data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakmap/set/index.md
--- title: WeakMap.prototype.set() slug: Web/JavaScript/Reference/Global_Objects/WeakMap/set page-type: javascript-instance-method browser-compat: javascript.builtins.WeakMap.set --- {{JSRef}} The **`set()`** method of {{jsxref("WeakMap")}} instances adds a new element with a specified key and value to this `WeakMap`. {{EmbedInteractiveExample("pages/js/weakmap-prototype-set.html")}} ## Syntax ```js-nolint set(key, value) ``` ### Parameters - `key` - : Must be either an object or a [non-registered symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry). The 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 - {{jsxref("TypeError")}} - : Thrown if `key` is not an object or a [non-registered symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry). ## Examples ### Using the 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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("WeakMap")}} - {{jsxref("WeakMap.prototype.get()")}} - {{jsxref("WeakMap.prototype.has()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakmap
data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakmap/weakmap/index.md
--- title: WeakMap() constructor slug: Web/JavaScript/Reference/Global_Objects/WeakMap/WeakMap page-type: javascript-constructor browser-compat: javascript.builtins.WeakMap.WeakMap --- {{JSRef}} The **`WeakMap()`** constructor creates {{jsxref("WeakMap")}} objects. ## Syntax ```js-nolint new WeakMap() new WeakMap(iterable) ``` > **Note:** `WeakMap()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}. ### Parameters - `iterable` - : An [`Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) or other iterable object that implements an [@@iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `WeakMap` in `core-js`](https://github.com/zloirock/core-js#weakmap) - [`WeakMap` in the JavaScript guide](/en-US/docs/Web/JavaScript/Guide/Keyed_collections#weakmap_object) - [Hiding Implementation Details with ECMAScript 6 WeakMaps](https://fitzgeraldnick.com/2014/01/13/hiding-implementation-details-with-e6-weakmaps.html) - {{jsxref("Map")}} - {{jsxref("Set")}} - {{jsxref("WeakSet")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakmap
data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakmap/delete/index.md
--- title: WeakMap.prototype.delete() slug: Web/JavaScript/Reference/Global_Objects/WeakMap/delete page-type: javascript-instance-method browser-compat: javascript.builtins.WeakMap.delete --- {{JSRef}} The **`delete()`** method of {{jsxref("WeakMap")}} instances removes the specified element from this `WeakMap`. {{EmbedInteractiveExample("pages/js/weakmap-prototype-delete.html")}} ## Syntax ```js-nolint 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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry). ## 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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("WeakMap")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/generatorfunction/index.md
--- title: GeneratorFunction slug: Web/JavaScript/Reference/Global_Objects/GeneratorFunction page-type: javascript-class browser-compat: javascript.builtins.GeneratorFunction --- {{JSRef}} The **`GeneratorFunction`** object provides methods for [generator functions](/en-US/docs/Web/JavaScript/Reference/Statements/function*). In JavaScript, every generator function is actually a `GeneratorFunction` object. Note that `GeneratorFunction` is _not_ a global object. It can be obtained with the following code: ```js const GeneratorFunction = function* () {}.constructor; ``` `GeneratorFunction` is a subclass of {{jsxref("Function")}}. {{EmbedInteractiveExample("pages/js/functionasterisk-function.html", "taller")}} ## Constructor - {{jsxref("GeneratorFunction/GeneratorFunction", "GeneratorFunction()")}} - : Creates a new `GeneratorFunction` object. ## Instance properties _Also inherits instance properties from its parent {{jsxref("Function")}}_. These properties are defined on `GeneratorFunction.prototype` and shared by all `GeneratorFunction` instances. - {{jsxref("Object/constructor", "GeneratorFunction.prototype.constructor")}} - : The constructor function that created the instance object. For `GeneratorFunction` instances, the initial value is the {{jsxref("GeneratorFunction/GeneratorFunction", "GeneratorFunction")}} constructor. - `GeneratorFunction.prototype.prototype` - : All generator functions share the same [`prototype`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype) property, which is [`Generator.prototype`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator). Each generator function instance also has its own `prototype` property. When the generator function is called, the returned generator object inherits from the generator function's `prototype` property, which in turn inherits from `GeneratorFunction.prototype.prototype`. - `GeneratorFunction.prototype[@@toStringTag]` - : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"GeneratorFunction"`. This property is used in {{jsxref("Object.prototype.toString()")}}. ## Instance methods _Inherits instance methods from its parent {{jsxref("Function")}}_. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`function*`](/en-US/docs/Web/JavaScript/Reference/Statements/function*) - [`function*` expression](/en-US/docs/Web/JavaScript/Reference/Operators/function*) - {{jsxref("Function")}} - {{jsxref("AsyncFunction")}} - {{jsxref("AsyncGeneratorFunction")}} - {{jsxref("Functions", "Functions", "", 1)}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/generatorfunction
data/mdn-content/files/en-us/web/javascript/reference/global_objects/generatorfunction/generatorfunction/index.md
--- title: GeneratorFunction() constructor slug: Web/JavaScript/Reference/Global_Objects/GeneratorFunction/GeneratorFunction page-type: javascript-constructor browser-compat: javascript.builtins.GeneratorFunction.GeneratorFunction --- {{JSRef}} The **`GeneratorFunction()`** constructor creates {{jsxref("GeneratorFunction")}} objects. Note that `GeneratorFunction` is _not_ a global object. It can be obtained with the following code: ```js const GeneratorFunction = function* () {}.constructor; ``` The `GeneratorFunction()` constructor is not intended to be used directly, and all caveats mentioned in the {{jsxref("Function/Function", "Function()")}} description apply to `GeneratorFunction()`. ## Syntax ```js-nolint new GeneratorFunction(functionBody) new GeneratorFunction(arg1, functionBody) new GeneratorFunction(arg1, arg2, functionBody) new GeneratorFunction(arg1, arg2, /* …, */ argN, functionBody) GeneratorFunction(functionBody) GeneratorFunction(arg1, functionBody) GeneratorFunction(arg1, arg2, functionBody) GeneratorFunction(arg1, arg2, /* …, */ argN, functionBody) ``` > **Note:** `GeneratorFunction()` can be called with or without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Both create a new `GeneratorFunction` instance. ### Parameters See {{jsxref("Function/Function", "Function()")}}. ## Examples ### Creating and using a GeneratorFunction() constructor ```js const GeneratorFunction = function* () {}.constructor; const g = new GeneratorFunction("a", "yield a * 2"); const iterator = g(10); console.log(iterator.next().value); // 20 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`function*`](/en-US/docs/Web/JavaScript/Reference/Statements/function*) - [`function*` expression](/en-US/docs/Web/JavaScript/Reference/Operators/function*) - [`Function()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function) - [Iterators and generators](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators) guide - {{jsxref("Functions", "Functions", "", 1)}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/uint8clampedarray/index.md
--- title: Uint8ClampedArray slug: Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray page-type: javascript-class browser-compat: javascript.builtins.Uint8ClampedArray --- {{JSRef}} The **`Uint8ClampedArray`** typed array represents an array of 8-bit unsigned integers clamped to 0–255. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). `Uint8ClampedArray` is a subclass of the hidden {{jsxref("TypedArray")}} class. ## Constructor - {{jsxref("Uint8ClampedArray/Uint8ClampedArray", "Uint8ClampedArray()")}} - : Creates a new `Uint8ClampedArray` object. ## Static properties _Also inherits static properties from its parent {{jsxref("TypedArray")}}_. - {{jsxref("TypedArray/BYTES_PER_ELEMENT", "Uint8ClampedArray.BYTES_PER_ELEMENT")}} - : Returns a number value of the element size. `1` in the case of `Uint8ClampedArray`. ## Static methods _Inherits static methods from its parent {{jsxref("TypedArray")}}_. ## Instance properties _Also inherits instance properties from its parent {{jsxref("TypedArray")}}_. These properties are defined on `Uint8ClampedArray.prototype` and shared by all `Uint8ClampedArray` instances. - {{jsxref("TypedArray/BYTES_PER_ELEMENT", "Uint8ClampedArray.prototype.BYTES_PER_ELEMENT")}} - : Returns a number value of the element size. `1` in the case of a `Uint8ClampedArray`. - {{jsxref("Object/constructor", "Uint8ClampedArray.prototype.constructor")}} - : The constructor function that created the instance object. For `Uint8ClampedArray` instances, the initial value is the {{jsxref("Uint8ClampedArray/Uint8ClampedArray", "Uint8ClampedArray")}} constructor. ## Instance methods _Inherits instance methods from its parent {{jsxref("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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Uint8ClampedArray` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays) - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("TypedArray")}} - {{jsxref("ArrayBuffer")}} - {{jsxref("DataView")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/uint8clampedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/uint8clampedarray/uint8clampedarray/index.md
--- title: Uint8ClampedArray() constructor slug: Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray/Uint8ClampedArray page-type: javascript-constructor browser-compat: javascript.builtins.Uint8ClampedArray.Uint8ClampedArray --- {{JSRef}} The **`Uint8ClampedArray()`** constructor creates {{jsxref("Uint8ClampedArray")}} objects. The contents are initialized to `0`. ## Syntax ```js-nolint 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`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}. ### Parameters See [`TypedArray`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ## Examples ### Different ways to create a 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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Uint8ClampedArray` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays) - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("TypedArray")}} - {{jsxref("ArrayBuffer")}} - {{jsxref("DataView")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/error/index.md
--- title: Error slug: Web/JavaScript/Reference/Global_Objects/Error page-type: javascript-class browser-compat: javascript.builtins.Error --- {{JSRef}} **`Error`** objects are thrown when runtime errors occur. The `Error` object can also be used as a base object for user-defined exceptions. See below for standard built-in error types. ## Description Runtime errors result in new `Error` objects being created and thrown. `Error` is a {{Glossary("serializable object")}}, so it can be cloned with {{domxref("structuredClone()")}} or copied between [Workers](/en-US/docs/Web/API/Worker) using {{domxref("Worker/postMessage()", "postMessage()")}}. ### Error types Besides the generic `Error` constructor, there are other core error constructors in JavaScript. For client-side exceptions, see [Exception handling statements](/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#exception_handling_statements). - {{jsxref("EvalError")}} - : Creates an instance representing an error that occurs regarding the global function {{jsxref("Global_Objects/eval", "eval()")}}. - {{jsxref("RangeError")}} - : Creates an instance representing an error that occurs when a numeric variable or parameter is outside its valid range. - {{jsxref("ReferenceError")}} - : Creates an instance representing an error that occurs when de-referencing an invalid reference. - {{jsxref("SyntaxError")}} - : Creates an instance representing a syntax error. - {{jsxref("TypeError")}} - : Creates an instance representing an error that occurs when a variable or parameter is not of a valid type. - {{jsxref("URIError")}} - : Creates an instance representing an error that occurs when {{jsxref("encodeURI()")}} or {{jsxref("decodeURI()")}} are passed invalid parameters. - {{jsxref("AggregateError")}} - : Creates an instance representing several errors wrapped in a single error when multiple errors need to be reported by an operation, for example by {{jsxref("Promise.any()")}}. - {{jsxref("InternalError")}} {{non-standard_inline}} - : Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion". ## Constructor - {{jsxref("Error/Error", "Error()")}} - : Creates a new `Error` object. ## Static methods - `Error.captureStackTrace()` {{non-standard_inline}} - : A non-standard V8 function that creates the {{jsxref("Error/stack", "stack")}} property on an Error instance. - `Error.stackTraceLimit` {{non-standard_inline}} - : A non-standard V8 numerical property that limits how many stack frames to include in an error stacktrace. - `Error.prepareStackTrace()` {{non-standard_inline}} {{optional_inline}} - : A non-standard V8 function that, if provided by usercode, is called by the V8 JavaScript engine for thrown exceptions, allowing the user to provide custom formatting for stacktraces. ## Instance properties These properties are defined on `Error.prototype` and shared by all `Error` instances. - {{jsxref("Object/constructor", "Error.prototype.constructor")}} - : The constructor function that created the instance object. For `Error` instances, the initial value is the {{jsxref("Error/Error", "Error")}} constructor. - {{jsxref("Error.prototype.name")}} - : Represents the name for the type of error. For `Error.prototype.name`, the initial value is `"Error"`. Subclasses like {{jsxref("TypeError")}} and {{jsxref("SyntaxError")}} provide their own `name` properties. - {{jsxref("Error.prototype.stack")}} {{non-standard_inline}} - : A non-standard property for a stack trace. These properties are own properties of each `Error` instance. - {{jsxref("Error/cause", "cause")}} - : Error cause indicating the reason why the current error is thrown — usually another caught error. For user-created `Error` objects, this is the value provided as the `cause` property of the constructor's second argument. - {{jsxref("Error/columnNumber", "columnNumber")}} {{non-standard_inline}} - : A non-standard Mozilla property for the column number in the line that raised this error. - {{jsxref("Error/fileName", "fileName")}} {{non-standard_inline}} - : A non-standard Mozilla property for the path to the file that raised this error. - {{jsxref("Error/lineNumber", "lineNumber")}} {{non-standard_inline}} - : A non-standard Mozilla property for the line number in the file that raised this error. - {{jsxref("Error/message", "message")}} - : Error message. For user-created `Error` objects, this is the string provided as the constructor's first argument. ## Instance methods - {{jsxref("Error.prototype.toString()")}} - : Returns a string representing the specified object. Overrides the {{jsxref("Object.prototype.toString()")}} method. ## Examples ### Throwing a generic error Usually you create an `Error` object with the intention of raising it using the {{jsxref("Statements/throw", "throw")}} keyword. You can handle the error using the {{jsxref("Statements/try...catch", "try...catch")}} construct: ```js try { throw new Error("Whoops!"); } catch (e) { console.error(`${e.name}: ${e.message}`); } ``` ### Handling a specific error type You can choose to handle only specific error types by testing the error type with the {{jsxref("Operators/instanceof", "instanceof")}} keyword: ```js try { foo.bar(); } catch (e) { if (e instanceof EvalError) { console.error(`${e.name}: ${e.message}`); } else if (e instanceof RangeError) { console.error(`${e.name}: ${e.message}`); } // etc. else { // If none of our cases matched leave the Error unhandled throw e; } } ``` ### Differentiate between similar errors Sometimes a block of code can fail for reasons that require different handling, but which throw very similar errors (i.e. with the same type and message). If you don't have control over the original errors that are thrown, one option is to catch them and throw new `Error` objects that have more specific messages. The original error should be passed to the new `Error` in the constructor's [`options`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Error#options) parameter as its `cause` property. This ensures that the original error and stack trace are available to higher-level try/catch blocks. The example below shows this for two methods that would otherwise fail with similar errors (`doFailSomeWay()` and `doFailAnotherWay()`): ```js function doWork() { try { doFailSomeWay(); } catch (err) { throw new Error("Failed in some way", { cause: err }); } try { doFailAnotherWay(); } catch (err) { throw new Error("Failed in another way", { cause: err }); } } try { doWork(); } catch (err) { switch (err.message) { case "Failed in some way": handleFailSomeWay(err.cause); break; case "Failed in another way": handleFailAnotherWay(err.cause); break; } } ``` > **Note:** If you are making a library, you should prefer to use error cause to discriminate between different errors emitted — rather than asking your consumers to parse the error message. See the [error cause page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause#providing_structured_data_as_the_error_cause) for an example. [Custom error types](#custom_error_types) can also use the `cause` property, provided the subclasses' constructor passes the `options` parameter when calling `super()`. The `Error()` base class constructor will read `options.cause` and define the `cause` property on the new error instance. ```js class MyError extends Error { constructor(message, options) { // Need to pass `options` as the second parameter to install the "cause" property. super(message, options); } } console.log(new MyError("test", { cause: new Error("cause") }).cause); // Error: cause ``` ### Custom error types You might want to define your own error types deriving from `Error` to be able to `throw new MyError()` and use `instanceof MyError` to check the kind of error in the exception handler. This results in cleaner and more consistent error handling code. See ["What's a good way to extend Error in JavaScript?"](https://stackoverflow.com/questions/1382107/whats-a-good-way-to-extend-error-in-javascript) on StackOverflow for an in-depth discussion. > **Warning:** Builtin subclassing cannot be reliably transpiled to pre-ES6 code, because there's no way to construct the base class with a particular `new.target` without {{jsxref("Reflect.construct()")}}. You need [additional configuration](https://github.com/loganfsmyth/babel-plugin-transform-builtin-extend) or manually call {{jsxref("Object/setPrototypeOf", "Object.setPrototypeOf(this, CustomError.prototype)")}} at the end of the constructor; otherwise, the constructed instance will not be a `CustomError` instance. See [the TypeScript FAQ](https://github.com/microsoft/TypeScript/wiki/FAQ#why-doesnt-extending-built-ins-like-error-array-and-map-work) for more information. > **Note:** Some browsers include the `CustomError` constructor in the stack trace when using ES2015 classes. ```js class CustomError extends Error { constructor(foo = "bar", ...params) { // Pass remaining arguments (including vendor specific ones) to parent constructor super(...params); // Maintains proper stack trace for where our error was thrown (only available on V8) if (Error.captureStackTrace) { Error.captureStackTrace(this, CustomError); } this.name = "CustomError"; // Custom debugging information this.foo = foo; this.date = new Date(); } } try { throw new CustomError("baz", "bazMessage"); } catch (e) { console.error(e.name); // CustomError console.error(e.foo); // baz console.error(e.message); // bazMessage console.error(e.stack); // stacktrace } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Error` with `cause` support in `core-js`](https://github.com/zloirock/core-js#ecmascript-error) - {{jsxref("Statements/throw", "throw")}} - {{jsxref("Statements/try...catch", "try...catch")}} - [Stack trace API](https://v8.dev/docs/stack-trace-api) in the V8 docs
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/error
data/mdn-content/files/en-us/web/javascript/reference/global_objects/error/name/index.md
--- title: Error.prototype.name slug: Web/JavaScript/Reference/Global_Objects/Error/name page-type: javascript-instance-data-property browser-compat: javascript.builtins.Error.name --- {{JSRef}} The **`name`** data property of `Error.prototype` is shared by all {{jsxref("Error")}} instances. It represents the name for the type of error. For `Error.prototype.name`, the initial value is `"Error"`. Subclasses like {{jsxref("TypeError")}} and {{jsxref("SyntaxError")}} provide their own `name` properties. ## Value A string. For `Error.prototype.name`, the initial value is `"Error"`. {{js_property_attributes(1, 0, 1)}} ## Description By default, {{jsxref("Error")}} instances are given the name "Error". The `name` property, in addition to the {{jsxref("Error/message", "message")}} property, is used by the {{jsxref("Error.prototype.toString()")}} method to create a string representation of the error. ## Examples ### Throwing a custom error ```js const e = new Error("Malformed input"); // e.name is 'Error' e.name = "ParseError"; throw e; // e.toString() would return 'ParseError: Malformed input' ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Error.prototype.message")}} - {{jsxref("Error.prototype.toString()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/error
data/mdn-content/files/en-us/web/javascript/reference/global_objects/error/columnnumber/index.md
--- title: "Error: columnNumber" slug: Web/JavaScript/Reference/Global_Objects/Error/columnNumber page-type: javascript-instance-data-property status: - non-standard browser-compat: javascript.builtins.Error.columnNumber --- {{JSRef}} {{Non-standard_Header}} The **`columnNumber`** data property of an {{jsxref("Error")}} instance contains the column number in the line of the file that raised this error. ## Value A positive integer. {{js_property_attributes(1, 0, 1)}} ## Examples ### Using columnNumber ```js try { throw new Error("Could not parse input"); } catch (err) { console.log(err.columnNumber); // 9 } ``` ## Specifications Not part of any standard. ## Browser compatibility {{Compat}} ## See also - {{jsxref("Error.prototype.stack")}} - {{jsxref("Error.prototype.lineNumber")}} - {{jsxref("Error.prototype.fileName")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/error
data/mdn-content/files/en-us/web/javascript/reference/global_objects/error/tostring/index.md
--- title: Error.prototype.toString() slug: Web/JavaScript/Reference/Global_Objects/Error/toString page-type: javascript-instance-method browser-compat: javascript.builtins.Error.toString --- {{JSRef}} The **`toString()`** method of {{jsxref("Error")}} instances returns a string representing this error. ## Syntax ```js-nolint toString() ``` ### Parameters None. ### Return value A string representing the specified {{jsxref("Error")}} object. ## Description The {{jsxref("Error")}} object overrides the {{jsxref("Object.prototype.toString()")}} method inherited by all objects. Its semantics are as follows: ```js Error.prototype.toString = function () { if ( this === null || (typeof this !== "object" && typeof this !== "function") ) { throw new TypeError(); } let name = this.name; name = name === undefined ? "Error" : `${name}`; let msg = this.message; msg = msg === undefined ? "" : `${msg}`; if (name === "") { return msg; } if (msg === "") { return name; } return `${name}: ${msg}`; }; ``` ## Examples ### Using toString() ```js const e1 = new Error("fatal error"); console.log(e1.toString()); // "Error: fatal error" const e2 = new Error("fatal error"); e2.name = undefined; console.log(e2.toString()); // "Error: fatal error" const e3 = new Error("fatal error"); e3.name = ""; console.log(e3.toString()); // "fatal error" const e4 = new Error("fatal error"); e4.name = ""; e4.message = undefined; console.log(e4.toString()); // "" const e5 = new Error("fatal error"); e5.name = "hello"; e5.message = undefined; console.log(e5.toString()); // "hello" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Error.prototype.toString` with many bug fixes in `core-js`](https://github.com/zloirock/core-js#ecmascript-error)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/error
data/mdn-content/files/en-us/web/javascript/reference/global_objects/error/stack/index.md
--- title: Error.prototype.stack slug: Web/JavaScript/Reference/Global_Objects/Error/stack page-type: javascript-instance-data-property status: - non-standard browser-compat: javascript.builtins.Error.stack --- {{JSRef}} {{Non-standard_Header}} > **Note:** The `stack` property is de facto implemented by all major JavaScript engines, and [the JavaScript standards committee is looking to standardize it](https://github.com/tc39/proposal-error-stacks). You cannot rely on the precise content of the stack string due to implementation inconsistencies, but you can generally assume it exists and use it for debugging purposes. The non-standard **`stack`** property of an {{jsxref("Error")}} instance offers a trace of which functions were called, in what order, from which line and file, and with what arguments. The stack string proceeds from the most recent calls to earlier ones, leading back to the original global scope call. ## Value A string. Because the `stack` property is non-standard, implementations differ about where it's installed. - In Firefox, it's an accessor property on `Error.prototype`. - In Chrome and Safari, it's a data property on each `Error` instance, with the descriptor: {{js_property_attributes(1, 0, 1)}} ## Description Each JavaScript engine uses its own format for stack traces, but they are fairly consistent in their high-level structure. Every implementation uses a separate line in the stack to represent each function call. The call that directly caused the error is placed at the top, and the call that started the whole call chain is placed at the bottom. Below are some examples of stack traces: ```js function foo() { bar(); } function bar() { baz(); } function baz() { console.log(new Error().stack); } foo(); ``` ```plain #### JavaScriptCore [email protected]:10:24 [email protected]:6:6 [email protected]:2:6 global [email protected]:13:4 #### SpiderMonkey [email protected]:10:15 [email protected]:6:3 [email protected]:2:3 @filename.js:13:1 #### V8 Error at baz (filename.js:10:15) at bar (filename.js:6:3) at foo (filename.js:2:3) at filename.js:13:1 ``` Different engines set this value at different times. Most modern engines set it when the {{jsxref("Error")}} object is created. This means you can get the full call stack information within a function using the following: ```js function foo() { console.log(new Error().stack); } ``` Without having to throw an error and then catch it. In V8, the non-standard `Error.captureStackTrace()`, `Error.stackTraceLimit`, and `Error.prepareStackTrace()` APIs can be used to customize the stack trace. Read the [Stack trace API](https://v8.dev/docs/stack-trace-api) in the V8 docs for more information. Stack frames can be things other than explicit function calls, too. For example, event listeners, timeout jobs, and promise handlers all begin their own call chain. Source code within {{jsxref("Global_Objects/eval", "eval()")}} and {{jsxref("Function")}} constructor calls also appear in the stack: ```js console.log(new Function("return new Error('Function failed')")().stack); console.log("===="); console.log(eval("new Error('eval failed')").stack); ``` ```plain #### JavaScriptCore anonymous@ global [email protected]:1:65 ==== eval code@ eval@[native code] global [email protected]:3:17 #### SpiderMonkey [email protected] line 1 > Function:1:8 @filename.js:1:65 ==== @filename.js line 3 > eval:1:1 @filename.js:3:13 #### V8 Error: Function failed at eval (eval at <anonymous> (filename.js:1:13), <anonymous>:1:8) at filename.js:1:65 ==== Error: eval failed at eval (eval at <anonymous> (filename.js:3:13), <anonymous>:1:1) at filename.js:3:13 ``` In Firefox, you can use the `//# sourceURL` directive to name an eval source. See the Firefox [Debug eval sources](https://firefox-source-docs.mozilla.org/devtools-user/debugger/how_to/debug_eval_sources/index.html) docs and the [Naming `eval` Scripts with the `//# sourceURL` Directive](https://fitzgeraldnick.com/2014/12/05/name-eval-scripts.html) blog post for more details. ## Examples ### Using the stack property The following script demonstrates how to use the `stack` property to output a stack trace into your browser window. You can use this to check what your browser's stack structure looks like. ```html hidden <div id="output"></div> ``` ```css hidden #output { white-space: pre; font-family: monospace; } ``` ```js function trace() { throw new Error("trace() failed"); } function b() { trace(); } function a() { b(3, 4, "\n\n", undefined, {}); } try { a("first call, firstarg"); } catch (e) { document.getElementById("output").textContent = e.stack; } ``` {{EmbedLiveSample("Using_the_stack_property", "700", "200")}} ## Specifications Not part of any standard. ## Browser compatibility {{Compat}} ## See also - [TraceKit](https://github.com/csnover/TraceKit/) on GitHub - [stacktrace.js](https://github.com/stacktracejs/stacktrace.js) on GitHub - [Stack trace API](https://v8.dev/docs/stack-trace-api) in the V8 docs
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/error
data/mdn-content/files/en-us/web/javascript/reference/global_objects/error/linenumber/index.md
--- title: "Error: lineNumber" slug: Web/JavaScript/Reference/Global_Objects/Error/lineNumber page-type: javascript-instance-data-property status: - non-standard browser-compat: javascript.builtins.Error.lineNumber --- {{JSRef}} {{Non-standard_Header}} The **`lineNumber`** data property of an {{jsxref("Error")}} instance contains the line number in the file that raised this error. ## Value A positive integer. {{js_property_attributes(1, 0, 1)}} ## Examples ### Using lineNumber ```js try { throw new Error("Could not parse input"); } catch (err) { console.log(err.lineNumber); // 2 } ``` ### Alternative example using error event ```js window.addEventListener("error", (e) => { console.log(e.lineNumber); // 5 }); const e = new Error("Could not parse input"); throw e; ``` This is not a standard feature and lacks widespread support. See the browser compatibility table below. ## Specifications Not part of any standard. ## Browser compatibility {{Compat}} ## See also - {{jsxref("Error.prototype.stack")}} - {{jsxref("Error.prototype.columnNumber")}} - {{jsxref("Error.prototype.fileName")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/error
data/mdn-content/files/en-us/web/javascript/reference/global_objects/error/filename/index.md
--- title: "Error: fileName" slug: Web/JavaScript/Reference/Global_Objects/Error/fileName page-type: javascript-instance-data-property status: - non-standard browser-compat: javascript.builtins.Error.fileName --- {{JSRef}} {{Non-standard_Header}} The **`fileName`** data property of an {{jsxref("Error")}} instance contains the path to the file that raised this error. ## Value A string. {{js_property_attributes(1, 0, 1)}} ## Description This non-standard property contains the path to the file that raised this error. If called from a debugger context, the Firefox Developer Tools for example, "debugger eval code" is returned. ## Examples ### Using fileName ```js const e = new Error("Could not parse input"); throw e; // e.fileName could look like "file:///C:/example.html" ``` ## Specifications Not part of any standard. ## Browser compatibility {{Compat}} ## See also - {{jsxref("Error.prototype.stack")}} - {{jsxref("Error.prototype.columnNumber")}} - {{jsxref("Error.prototype.lineNumber")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/error
data/mdn-content/files/en-us/web/javascript/reference/global_objects/error/error/index.md
--- title: Error() constructor slug: Web/JavaScript/Reference/Global_Objects/Error/Error page-type: javascript-constructor browser-compat: javascript.builtins.Error.Error --- {{JSRef}} The **`Error()`** constructor creates {{jsxref("Error")}} objects. ## Syntax ```js-nolint new Error() new Error(message) new Error(message, options) new Error(message, fileName) new Error(message, fileName, lineNumber) Error() Error(message) Error(message, options) Error(message, fileName) Error(message, fileName, lineNumber) ``` > **Note:** `Error()` can be called with or without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Both create a new `Error` instance. ### Parameters - `message` {{optional_inline}} - : A human-readable description of the error. - `options` {{optional_inline}} - : An object that has the following properties: - `cause` {{optional_inline}} - : A value indicating the specific cause of the error, reflected in the {{jsxref("Error/cause", "cause")}} property. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. - `fileName` {{optional_inline}} {{non-standard_inline}} - : The path to the file that raised this error, reflected in the {{jsxref("Error/fileName", "fileName")}} property. Defaults to the name of the file containing the code that called the `Error()` constructor. - `lineNumber` {{optional_inline}} {{non-standard_inline}} - : The line number within the file on which the error was raised, reflected in the {{jsxref("Error/lineNumber", "lineNumber")}} property. Defaults to the line number containing the `Error()` constructor invocation. ## Examples ### Function call or new construction When `Error` is used like a function, that is without {{jsxref("Operators/new", "new")}}, it will return an `Error` object. Therefore, a mere call to `Error` will produce the same output that constructing an `Error` object via the `new` keyword would. ```js const x = Error("I was created using a function call!"); // above has the same functionality as following const y = new Error('I was constructed via the "new" keyword!'); ``` ### Rethrowing an error with a cause It is sometimes useful to catch an error and re-throw it with a new message. In this case you should pass the original error into the constructor for the new `Error`, as shown. ```js try { frameworkThatCanThrow(); } catch (err) { throw new Error("New error message", { cause: err }); } ``` For a more detailed example see [Error > Differentiate between similar errors](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#differentiate_between_similar_errors). ### Omitting options argument JavaScript only tries to read `options.cause` if `options` is an object — this avoids ambiguity with the other non-standard `Error(message, fileName, lineNumber)` signature, which requires the second parameter to be a string. If you omit `options`, pass a primitive value as `options`, or pass an object without the `cause` property, then the created `Error` object will have no `cause` property. ```js // Omitting options const error1 = new Error("Error message"); console.log("cause" in error1); // false // Passing a primitive value const error2 = new Error("Error message", ""); console.log("cause" in error2); // false // Passing an object without a cause property const error3 = new Error("Error message", { details: "http error" }); console.log("cause" in error3); // false ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Error` with `cause` support in `core-js`](https://github.com/zloirock/core-js#ecmascript-error) - {{jsxref("Statements/throw", "throw")}} - {{jsxref("Statements/try...catch", "try...catch")}} - [Error causes](https://v8.dev/features/error-cause) on v8.dev (2021)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/error
data/mdn-content/files/en-us/web/javascript/reference/global_objects/error/message/index.md
--- title: "Error: message" slug: Web/JavaScript/Reference/Global_Objects/Error/message page-type: javascript-instance-data-property browser-compat: javascript.builtins.Error.message --- {{JSRef}} The **`message`** data property of an {{jsxref("Error")}} instance is a human-readable description of the error. ## Value A string corresponding to the value passed to the [`Error()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Error) constructor as the first argument. {{js_property_attributes(1, 0, 1)}} ## Description This property contains a brief description of the error if one is available or has been set. The `message` property combined with the {{jsxref("Error/name", "name")}} property is used by the {{jsxref("Error.prototype.toString()")}} method to create a string representation of the Error. By default, the `message` property is an empty string, but this behavior can be overridden for an instance by specifying a message as the first argument to the {{jsxref("Error/Error", "Error")}} constructor. ## Examples ### Throwing a custom error ```js const e = new Error("Could not parse input"); // e.message is 'Could not parse input' throw e; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Error.prototype.name")}} - {{jsxref("Error.prototype.toString()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/error
data/mdn-content/files/en-us/web/javascript/reference/global_objects/error/cause/index.md
--- title: "Error: cause" slug: Web/JavaScript/Reference/Global_Objects/Error/cause page-type: javascript-instance-data-property browser-compat: javascript.builtins.Error.cause --- {{JSRef}} The **`cause`** data property of an {{jsxref("Error")}} instance indicates the specific original cause of the error. It is used when catching and re-throwing an error with a more-specific or useful error message in order to still have access to the original error. ## Value The value that was passed to the [`Error()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Error) constructor in the `options.cause` argument. It may not be present. {{js_property_attributes(1, 0, 1)}} ## Description The value of `cause` can be of any type. You should not make assumptions that the error you caught has an `Error` as its `cause`, in the same way that you cannot be sure the variable bound in the `catch` statement is an `Error` either. The "Providing structured data as the error cause" example below shows a case where a non-error is deliberately provided as the cause. ## Examples ### Rethrowing an error with a cause It is sometimes useful to catch an error and re-throw it with a new message. In this case you should pass the original error into the constructor for the new `Error`, as shown. ```js try { connectToDatabase(); } catch (err) { throw new Error("Connecting to database failed.", { cause: err }); } ``` For a more detailed example see [Error > Differentiate between similar errors](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#differentiate_between_similar_errors). ### Providing structured data as the error cause Error messages written for human consumption may be inappropriate for machine parsing — since they're subject to rewording or punctuation changes that may break any existing parsing written to consume them. So when throwing an error from a function, as an alternative to a human-readable error message, you can instead provide the cause as structured data, for machine parsing. ```js function makeRSA(p, q) { if (!Number.isInteger(p) || !Number.isInteger(q)) { throw new Error("RSA key generation requires integer inputs.", { cause: { code: "NonInteger", values: [p, q] }, }); } if (!areCoprime(p, q)) { throw new Error("RSA key generation requires two co-prime integers.", { cause: { code: "NonCoprime", values: [p, q] }, }); } // rsa algorithm… } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Error.prototype.message")}} - {{jsxref("Error.prototype.toString()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator/index.md
--- title: Iterator slug: Web/JavaScript/Reference/Global_Objects/Iterator page-type: javascript-class browser-compat: javascript.builtins.Iterator --- {{JSRef}} An **`Iterator`** object is an object that conforms to the [iterator protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol) by providing a `next()` method that returns an iterator result object. All built-in iterators inherit from the `Iterator` class. The `Iterator` class provides a [`@@iterator`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator/@@iterator) method that returns the iterator object itself, making the iterator also [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol). It also provides some helper methods for working with iterators. ## Description The following are all built-in JavaScript iterators: - The _Array Iterator_ returned by {{jsxref("Array.prototype.values()")}}, {{jsxref("Array.prototype.keys()")}}, {{jsxref("Array.prototype.entries()")}}, [`Array.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@iterator), {{jsxref("TypedArray.prototype.values()")}}, {{jsxref("TypedArray.prototype.keys()")}}, {{jsxref("TypedArray.prototype.entries()")}}, [`TypedArray.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/@@iterator), and [`arguments[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Functions/arguments/@@iterator). - The _String Iterator_ returned by [`String.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/@@iterator). - The _Map Iterator_ returned by {{jsxref("Map.prototype.values()")}}, {{jsxref("Map.prototype.keys()")}}, {{jsxref("Map.prototype.entries()")}}, and [`Map.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/@@iterator). - The _Set Iterator_ returned by {{jsxref("Set.prototype.values()")}}, {{jsxref("Set.prototype.keys()")}}, {{jsxref("Set.prototype.entries()")}}, and [`Set.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/@@iterator). - The _RegExp String Iterator_ returned by [`RegExp.prototype[@@matchAll]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll) and {{jsxref("String.prototype.matchAll()")}}. - The {{jsxref("Generator")}} object returned by [generator functions](/en-US/docs/Web/JavaScript/Reference/Statements/function*). - The _Segments Iterator_ returned by the [`[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment/Segments/@@iterator) method of the [`Segments`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment/Segments) object returned by [`Intl.Segmenter.prototype.segment()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment). - The _Iterator Helper_ returned by iterator helper methods such as {{jsxref("Iterator.prototype.filter()")}} and {{jsxref("Iterator.prototype.map()")}}. Each of these iterators have a distinct prototype object, which defines the `next()` method used by the particular iterator. For example, all string iterator objects inherit from a hidden object `StringIteratorPrototype`, which has a `next()` method that iterates this string by code points. `StringIteratorPrototype` also has a [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property whose initial value is the string `"String Iterator"`. This property is used in {{jsxref("Object.prototype.toString()")}}. Similarly, other iterator prototypes also have their own `@@toStringTag` values, which are the same as the names given above. All of these prototype objects inherit from `Iterator.prototype`, which provides a [`@@iterator`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator) method that returns the iterator object itself, making the iterator also [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol). ### Iterator helpers > **Note:** These methods are _iterator_ helpers, not _iterable_ helpers, because the only requirement for an object to be iterable is just the presence of a `@@iterator` method. There is no shared prototype to install these methods on. The `Iterator` class itself provides some helper methods for working with iterators. For example, you may be tempted to do the following: ```js const nameToDeposit = new Map([ ["Anne", 1000], ["Bert", 1500], ["Carl", 2000], ]); const totalDeposit = [...nameToDeposit.values()].reduce((a, b) => a + b); ``` This first converts the iterator returned by {{jsxref("Map.prototype.values()")}} to an array, then uses the {{jsxref("Array.prototype.reduce()")}} method to calculate the sum. However, this both creates an intermediate array and iterates the array twice. Instead, you can use the `reduce()` method of the iterator itself: ```js const totalDeposit = nameToDeposit.values().reduce((a, b) => a + b); ``` This method is more efficient, because it only iterates the iterator once, without memorizing any intermediate values. Iterator helper methods are necessary to work with infinite iterators: ```js function* fibonacci() { let current = 1; let next = 1; while (true) { yield current; [current, next] = [next, current + next]; } } const seq = fibonacci(); const firstThreeDigitTerm = seq.find((n) => n >= 100); ``` You cannot convert `seq` to an array, because it is infinite. Instead, you can use the `find()` method of the iterator itself, which only iterates `seq` as far as necessary to find the first value that satisfies the condition. You will find many iterator methods analogous to array methods, such as: | Iterator method | Array method | | ------------------------------------------ | --------------------------------------- | | {{jsxref("Iterator.prototype.every()")}} | {{jsxref("Array.prototype.every()")}} | | {{jsxref("Iterator.prototype.filter()")}} | {{jsxref("Array.prototype.filter()")}} | | {{jsxref("Iterator.prototype.find()")}} | {{jsxref("Array.prototype.find()")}} | | {{jsxref("Iterator.prototype.flatMap()")}} | {{jsxref("Array.prototype.flatMap()")}} | | {{jsxref("Iterator.prototype.forEach()")}} | {{jsxref("Array.prototype.forEach()")}} | | {{jsxref("Iterator.prototype.map()")}} | {{jsxref("Array.prototype.map()")}} | | {{jsxref("Iterator.prototype.reduce()")}} | {{jsxref("Array.prototype.reduce()")}} | | {{jsxref("Iterator.prototype.some()")}} | {{jsxref("Array.prototype.some()")}} | {{jsxref("Iterator.prototype.drop()")}} and {{jsxref("Iterator.prototype.take()")}} combined are somewhat analogous to {{jsxref("Array.prototype.slice()")}}. Among these methods, {{jsxref("Iterator/filter", "filter()")}}, {{jsxref("Iterator/flatMap", "flatMap()")}}, {{jsxref("Iterator/map", "map()")}}, {{jsxref("Iterator/drop", "drop()")}}, and {{jsxref("Iterator/take", "take()")}} return a new _Iterator Helper_ object. The iterator helper is also an `Iterator` instance, making the helper methods chainable. All iterator helper objects inherit from a common prototype object, which implements the iterator protocol: - `next()` - : Calls the `next()` method of the underlying iterator, applies the helper method to the result, and returns the result. - `return()` - : Calls the `return()` method of the underlying iterator, and returns the result. The iterator helper shares the same data source as the underlying iterator, so iterating the iterator helper causes the underlying iterator to be iterated as well. There is no way to "fork" an iterator to allow it to be iterated multiple times. ```js const it = [1, 2, 3].values(); const it2 = it.drop(0); // Essentially a copy console.log(it.next().value); // 1 console.log(it2.next().value); // 2 console.log(it.next().value); // 3 ``` ### Proper iterators There are two kinds of "iterators": objects that conform to the [iterator protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol) (which, at its minimum, only requires the presence of a `next()` method), and objects that inherit from the `Iterator` class, which enjoy the helper methods. They do not entail each other — objects that inherit from `Iterator` do not automatically become iterators, because the `Iterator` class does not define a `next()` method. Instead, the object needs to define a `next()` method itself. A _proper iterator_ is one that both conforms to the iterator protocol and inherits from `Iterator`, and most code expect iterators to be proper iterators and iterables to return proper iterators. To create proper iterators, define a class that extends {{jsxref("Iterator/Iterator", "Iterator")}}, or use the {{jsxref("Iterator.from()")}} method. ```js class MyIterator extends Iterator { next() { // … } } const myIterator = Iterator.from({ next() { // … }, }); ``` ## Constructor - {{jsxref("Iterator/Iterator", "Iterator()")}} {{experimental_inline}} - : Intended to be [extended](/en-US/docs/Web/JavaScript/Reference/Classes/extends) by other classes that create iterators. Throws an error when constructed by itself. ## Static methods - {{jsxref("Iterator.from()")}} {{experimental_inline}} - : Creates a new `Iterator` object from an iterator or iterable object. ## Instance properties These properties are defined on `Iterator.prototype` and shared by all `Iterator` instances. - {{jsxref("Object/constructor", "Iterator.prototype.constructor")}} - : The constructor function that created the instance object. For `Iterator` instances, the initial value is the {{jsxref("Iterator/Iterator", "Iterator")}} constructor. - `Iterator.prototype[@@toStringTag]` - : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"Iterator"`. This property is used in {{jsxref("Object.prototype.toString()")}}. > **Note:** Unlike the `@@toStringTag` on most built-in classes, `Iterator.prototype[@@toStringTag]` is writable for web compatibility reasons. ## Instance methods - {{jsxref("Iterator.prototype.drop()")}} {{experimental_inline}} - : Returns a new iterator helper that skips the given number of elements at the start of this iterator. - {{jsxref("Iterator.prototype.every()")}} {{experimental_inline}} - : Tests whether all elements produced by the iterator pass the test implemented by the provided function. - {{jsxref("Iterator.prototype.filter()")}} {{experimental_inline}} - : Returns a new iterator helper that yields only those elements of the iterator for which the provided callback function returns `true`. - {{jsxref("Iterator.prototype.find()")}} {{experimental_inline}} - : Returns the first element produced by the iterator that satisfies the provided testing function. If no values satisfy the testing function, {{jsxref("undefined")}} is returned. - {{jsxref("Iterator.prototype.flatMap()")}} {{experimental_inline}} - : Returns a new iterator helper that takes each element in the original iterator, runs it through a mapping function, and yields elements returned by the mapping function (which are contained in another iterator or iterable). - {{jsxref("Iterator.prototype.forEach()")}} {{experimental_inline}} - : Executes a provided function once for each element produced by the iterator. - {{jsxref("Iterator.prototype.map()")}} {{experimental_inline}} - : Returns a new iterator helper that yields elements of the iterator, each transformed by a mapping function. - {{jsxref("Iterator.prototype.reduce()")}} {{experimental_inline}} - : Executes a user-supplied "reducer" callback function on each element produced by the iterator, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements is a single value. - {{jsxref("Iterator.prototype.some()")}} {{experimental_inline}} - : Tests whether at least one element in the iterator passes the test implemented by the provided function. It returns a boolean value. - {{jsxref("Iterator.prototype.take()")}} {{experimental_inline}} - : Returns a new iterator helper that yields the given number of elements in this iterator and then terminates. - {{jsxref("Iterator.prototype.toArray()")}} {{experimental_inline}} - : Creates a new {{jsxref("Array")}} instance populated with the elements yielded from the iterator. - [`Iterator.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator/@@iterator) - : Returns the iterator object itself. This allows iterator objects to also be iterable. ## Examples ### Using an iterator as an iterable All built-in iterators are also iterable, so you can use them in a `for...of` loop: ```js const arrIterator = [1, 2, 3].values(); for (const value of arrIterator) { console.log(value); } // Logs: 1, 2, 3 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Iterator` in `core-js`](https://github.com/zloirock/core-js#iterator-helpers) - {{jsxref("Statements/function*", "function*")}} - [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator/flatmap/index.md
--- title: Iterator.prototype.flatMap() slug: Web/JavaScript/Reference/Global_Objects/Iterator/flatMap page-type: javascript-instance-method status: - experimental browser-compat: javascript.builtins.Iterator.flatMap --- {{JSRef}}{{SeeCompatTable}} The **`flatMap()`** method of {{jsxref("Iterator")}} instances returns a new [iterator helper](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator#iterator_helpers) that takes each element in the original iterator, runs it through a mapping function, and yields elements returned by the mapping function (which are contained in another iterator or iterable). ## Syntax ```js-nolint flatMap(callbackFn) ``` ### Parameters - `callbackFn` - : A function to execute for each element produced by the iterator. It should return an iterator or iterable that yields elements to be yielded by `flatMap()`, or a single non-iterator/iterable value to be yielded. The function is called with the following arguments: - `element` - : The current element being processed in the array. - `index` - : The index of the current element being processed in the array. ### Return value A new [iterator helper](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator#iterator_helpers). The first time the iterator helper's `next()` method is called, it calls `callbackFn` on the first element produced by the underlying iterator, and the return value, which should be an iterator or iterable, is yielded one-by-one by the iterator helper (like {{jsxref("Operators/yield*", "yield*")}}). The next element is fetched from the underlying iterator when the previous one returned by `callbackFn` is completed. When the underlying iterator is completed, the iterator helper is also completed (the `next()` method produces `{ value: undefined, done: true }`). ### Exceptions - {{jsxref("TypeError")}} - : Thrown if `callbackFn` returns a non-iterator/iterable value or a string primitive. ## Description `flatMap` accepts two kinds of return values from `callbackFn`: an iterator or iterable. They are handled in the same way as {{jsxref("Iterator.from()")}}: if the return value is iterable, the `@@iterator` method is called and the return value is used; otherwise, the return value is treated as an iterator and its `next()` method is called. ```js [1, 2, 3] .values() .flatMap((x) => { let itDone = false; const it = { next() { if (itDone) { return { value: undefined, done: true }; } itDone = true; return { value: x, done: false }; }, }; switch (x) { case 1: // An iterable that's not an iterator return { [Symbol.iterator]: () => it }; case 2: // An iterator that's not an iterable return it; case 3: // An iterable iterator is treated as an iterable return { ...it, [Symbol.iterator]() { console.log("@@iterator called"); return it; }, }; } }) .toArray(); // Logs "@@iterator called" // Returns [1, 2, 3] ``` ## Examples ### Merging maps The following example merges two {{jsxref("Map")}} objects into one: ```js const map1 = new Map([ ["a", 1], ["b", 2], ["c", 3], ]); const map2 = new Map([ ["d", 4], ["e", 5], ["f", 6], ]); const merged = new Map([map1, map2].values().flatMap((x) => x)); console.log(merged.get("a")); // 1 console.log(merged.get("e")); // 5 ``` This avoids creating any temporary copies of the map's content. Note that the array `[map1, map2]` must first be converted to an iterator (using {{jsxref("Array.prototype.values()")}}), because {{jsxref("Array.prototype.flatMap()")}} only flattens arrays, not iterables. ```js new Map([map1, map2].flatMap((x) => x)); // Map(1) {undefined => undefined} ``` ### Returning strings Strings are iterable, but `flatMap()` specifically rejects string primitives returned from `callbackFn`, this is because the behavior of iterating by code points is often not what you want. ```js example-bad [1, 2, 3] .values() .flatMap((x) => String(x)) .toArray(); // TypeError: Iterator.prototype.flatMap called on non-object ``` You may want to wrap it in an array instead so the entire string is yielded as one: ```js [1, 2, 3] .values() .flatMap((x) => [String(x)]) .toArray(); // ['1', '2', '3'] ``` Or, if the behavior of iterating by code points is intended, you can use {{jsxref("Iterator.from()")}} to convert it to a proper iterator: ```js [1, 2, 3] .values() .flatMap((x) => Iterator.from(String(x * 10))) .toArray(); // ['1', '0', '2', '0', '3', '0'] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Iterator.prototype.flatMap` in `core-js`](https://github.com/zloirock/core-js#iterator-helpers)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator/map/index.md
--- title: Iterator.prototype.map() slug: Web/JavaScript/Reference/Global_Objects/Iterator/map page-type: javascript-instance-method status: - experimental browser-compat: javascript.builtins.Iterator.map --- {{JSRef}}{{SeeCompatTable}} The **`map()`** method of {{jsxref("Iterator")}} instances returns a new [iterator helper](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator#iterator_helpers) that yields elements of the iterator, each transformed by a mapping function. ## Syntax ```js-nolint map(callbackFn) ``` ### Parameters - `callbackFn` - : A function to execute for each element produced by the iterator. Its return value is yielded by the iterator helper. The function is called with the following arguments: - `element` - : The current element being processed. - `index` - : The index of the current element being processed. ### Return value A new [iterator helper](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator#iterator_helpers). Each time the iterator helper's `next()` method is called, it gets the next element from the underlying iterator, applies `callbackFn`, and yields the return value. When the underlying iterator is completed, the iterator helper is also completed (the `next()` method produces `{ value: undefined, done: true }`). ## Description The main advantage of iterator helpers over array methods is their ability to work with infinite iterators. With infinite iterators, `map()` allows you to create a new iterator that, when iterated, produces transformed elements. ## Examples ### Using map() The following example creates an iterator that yields terms in the Fibonacci sequence, transforms it into a new sequence with each term squared, and then reads the first few terms: ```js function* fibonacci() { let current = 1; let next = 1; while (true) { yield current; [current, next] = [next, current + next]; } } const seq = fibonacci().map((x) => x ** 2); console.log(seq.next().value); // 1 console.log(seq.next().value); // 1 console.log(seq.next().value); // 4 ``` ### Using map() with a for...of loop `map()` is most convenient when you are not hand-rolling the iterator. Because iterators are also iterable, you can iterate the returned helper with a {{jsxref("Statements/for...of", "for...of")}} loop: ```js for (const n of fibonacci().map((x) => x ** 2)) { console.log(n); if (n > 30) { break; } } // Logs: // 1 // 1 // 4 // 9 // 25 // 64 ``` This is equivalent to: ```js for (const n of fibonacci()) { const n2 = n ** 2; console.log(n2); if (n2 > 30) { break; } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Iterator.prototype.map` in `core-js`](https://github.com/zloirock/core-js#iterator-helpers)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator/from/index.md
--- title: Iterator.from() slug: Web/JavaScript/Reference/Global_Objects/Iterator/from page-type: javascript-static-method status: - experimental browser-compat: javascript.builtins.Iterator.from --- {{JSRef}}{{SeeCompatTable}} The **`Iterator.from()`** static method creates a new {{jsxref("Iterator")}} object from an iterator or iterable object. ## Syntax ```js-nolint from(object) ``` ### Parameters - `object` - : An object that implements the [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) protocol or the [iterator](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol) protocol. ### Return value If `object` is an iterable, its `@@iterator` method is called to obtain the iterator. Otherwise, `object` is assumed to be an iterator. If the iterator is already {{jsxref("Operators/instanceof", "instanceof")}} {{jsxref("Iterator")}} (which means it has `Iterator.prototype` in its prototype chain), it is returned directly. Otherwise, a new {{jsxref("Iterator")}} object is created that wraps the original iterator. ## Description This method exists to convert custom iterators, probably exported by libraries, to [proper iterators](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator#proper_iterators). All iterator objects returned by `Iterator.from()` inherit from a common prototype object, which has the following methods: - `next()` - : Calls the underlying iterator's `next()` method and returns the result. - `return()` - : Calls the underlying iterator's `return()` method and returns the result, or returns `{ value: undefined, done: true }` if the underlying iterator doesn't have a `return()` method. ## Examples ### Converting an iterable to a proper iterator Because `obj` is already an iterable that returns a proper iterator when its `@@iterator` method is called, `Iterator.from(obj)` returns the same iterator. ```js const iterator = (function* () { yield 1; yield 2; yield 3; })(); const obj = { [Symbol.iterator]() { return iterator; }, }; const iterator2 = Iterator.from(obj); console.log(iterator2 === iterator); // true ``` Because `obj2` is an iterable that returns a non-proper iterator when its `@@iterator` method is called, `Iterator.from(obj2)` returns a new iterator that wraps the original iterator. ```js const iterator = { current: 0, next() { return { value: this.current++, done: false }; }, }; const obj2 = { [Symbol.iterator]() { return iterator; }, }; const iterator2 = Iterator.from(obj2); console.log(iterator2 === iterator); // false console.log(iterator2.next()); // { value: 0, done: false } console.log(iterator.next()); // { value: 1, done: false } ``` ### Converting an iterator to a proper iterator Because `obj` is already a proper iterator, `Iterator.from(obj)` returns itself. ```js const obj = (function* () { yield 1; yield 2; yield 3; })(); const iterator = Iterator.from(obj); console.log(iterator === obj); // true ``` Because `obj2` is a non-proper iterator, `Iterator.from(obj2)` returns a new iterator that wraps the original iterator. ```js const obj2 = { current: 0, next() { return { value: this.current++, done: false }; }, }; const iterator = Iterator.from(obj2); console.log(iterator === obj2); // false console.log(iterator.next()); // { value: 0, done: false } console.log(obj2.next()); // { value: 1, done: false } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Iterator.from` in `core-js`](https://github.com/zloirock/core-js#iterator-helpers) - {{jsxref("Iterator")}} - {{jsxref("Array.from()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator/find/index.md
--- title: Iterator.prototype.find() slug: Web/JavaScript/Reference/Global_Objects/Iterator/find page-type: javascript-instance-method status: - experimental browser-compat: javascript.builtins.Iterator.find --- {{JSRef}}{{SeeCompatTable}} The **`find()`** method of {{jsxref("Iterator")}} instances is similar to {{jsxref("Array.prototype.find()")}}: it returns the first element produced by the iterator that satisfies the provided testing function. If no values satisfy the testing function, {{jsxref("undefined")}} is returned. ## Syntax ```js-nolint find(callbackFn) ``` ### Parameters - `callbackFn` - : A function to execute for each element produced by the iterator. It should return a [truthy](/en-US/docs/Glossary/Truthy) value to indicate a matching element has been found, and a [falsy](/en-US/docs/Glossary/Falsy) value otherwise. The function is called with the following arguments: - `element` - : The current element being processed. - `index` - : The index of the current element being processed. ### Return value The first element produced by the iterator that satisfies the provided testing function. Otherwise, {{jsxref("undefined")}} is returned. ## Description `find()` iterates the iterator and invokes the `callbackFn` function once for each element. It returns the element immediately if the callback function returns a truthy value. Otherwise, it iterates until the end of the iterator and returns `undefined`. If `find()` returns an element, the underlying iterator is closed by calling its `return()` method. The main advantage of iterator helpers over array methods is their ability to work with infinite iterators. With infinite iterators, `find()` returns the first satisfying element as soon as it is found. If the `callbackFn` always returns a falsy value, the method never returns. ## Examples ### Using find() ```js function* fibonacci() { let current = 1; let next = 1; while (true) { yield current; [current, next] = [next, current + next]; } } const isEven = (x) => x % 2 === 0; console.log(fibonacci().find(isEven)); // 2 const isNegative = (x) => x < 0; console.log(fibonacci().take(10).find(isNegative)); // undefined console.log(fibonacci().find(isNegative)); // Never completes ``` Calling `find()` always closes the underlying iterator, even if the method early-returns. The iterator is never left in a half-way state. ```js const seq = fibonacci(); console.log(seq.find(isEven)); // 2 console.log(seq.next()); // { value: undefined, done: true } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Iterator.prototype.find` in `core-js`](https://github.com/zloirock/core-js#iterator-helpers) - {{jsxref("Iterator")}} - {{jsxref("Iterator.prototype.every()")}} - {{jsxref("Iterator.prototype.some()")}} - {{jsxref("Array.prototype.find()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator/take/index.md
--- title: Iterator.prototype.take() slug: Web/JavaScript/Reference/Global_Objects/Iterator/take page-type: javascript-instance-method status: - experimental browser-compat: javascript.builtins.Iterator.take --- {{JSRef}}{{SeeCompatTable}} The **`take()`** method of {{jsxref("Iterator")}} instances returns a new [iterator helper](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator#iterator_helpers) that yields the given number of elements in this iterator and then terminates. ## Syntax ```js-nolint take(limit) ``` ### Parameters - `limit` - : The number of elements to take from the start of the iteration. ### Return value A new [iterator helper](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator#iterator_helpers). The returned iterator helper yields the elements in the original iterator one-by-one, and then completes (the `next()` method produces `{ value: undefined, done: true }`) once `limit` elements have been yielded, or when the original iterator is exhausted, whichever comes first. ### Exceptions - {{jsxref("RangeError")}} - : Thrown if `limit` becomes {{jsxref("NaN")}} or negative when [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). ## Examples ### Using take() The following example creates an iterator that yields terms in the Fibonacci sequence, and then logs the first three terms: ```js function* fibonacci() { let current = 1; let next = 1; while (true) { yield current; [current, next] = [next, current + next]; } } const seq = fibonacci().take(3); console.log(seq.next().value); // 1 console.log(seq.next().value); // 1 console.log(seq.next().value); // 2 console.log(seq.next().value); // undefined ``` ### Using take() with a for...of loop `take()` is most convenient when you are not hand-rolling the iterator. Because iterators are also iterable, you can iterate the returned helper with a {{jsxref("Statements/for...of", "for...of")}} loop: ```js for (const n of fibonacci().take(5)) { console.log(n); } // Logs: // 1 // 1 // 2 // 3 // 5 ``` Because `fibonacci()` is an infinite iterator, you can't use a `for` loop to iterate it directly. ### Combining drop() with take() You can combine `take()` with {{jsxref("Iterator.prototype.drop()")}} to get a slice of an iterator: ```js for (const n of fibonacci().drop(2).take(5)) { // Drops the first two elements, then takes the next five console.log(n); } // Logs: // 2 // 3 // 5 // 8 // 13 for (const n of fibonacci().take(5).drop(2)) { // Takes the first five elements, then drops the first two console.log(n); } // Logs: // 2 // 3 // 5 ``` ### Lower and upper bounds of take count When the `limit` is negative or {{jsxref("NaN")}}, a {{jsxref("RangeError")}} is thrown: ```js fibonacci().take(-1); // RangeError: -1 must be positive fibonacci().take(undefined); // RangeError: undefined must be positive ``` When the `limit` is larger than the total number of elements the iterator can produce (such as {{jsxref("Infinity")}}), the returned iterator helper has essentially the same behavior as the original iterator: ```js for (const n of new Set([1, 2, 3]).values().take(Infinity)) { console.log(n); } // Logs: // 1 // 2 // 3 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Iterator.prototype.take` in `core-js`](https://github.com/zloirock/core-js#iterator-helpers) - {{jsxref("Iterator")}} - {{jsxref("Iterator.prototype.drop()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator/every/index.md
--- title: Iterator.prototype.every() slug: Web/JavaScript/Reference/Global_Objects/Iterator/every page-type: javascript-instance-method status: - experimental browser-compat: javascript.builtins.Iterator.every --- {{JSRef}}{{SeeCompatTable}} The **`every()`** method of {{jsxref("Iterator")}} instances is similar to {{jsxref("Array.prototype.every()")}}: it tests whether all elements produced by the iterator pass the test implemented by the provided function. It returns a boolean value. ## Syntax ```js-nolint every(callbackFn) ``` ### Parameters - `callbackFn` - : A function to execute for each element produced by the iterator. It should return a [truthy](/en-US/docs/Glossary/Truthy) value to indicate the element passes the test, and a [falsy](/en-US/docs/Glossary/Falsy) value otherwise. The function is called with the following arguments: - `element` - : The current element being processed. - `index` - : The index of the current element being processed. ### Return value `true` if `callbackFn` returns a {{Glossary("truthy")}} value for every element. Otherwise, `false`. ## Description `every()` iterates the iterator and invokes the `callbackFn` function once for each element. It returns `false` immediately if the callback function returns a falsy value. Otherwise, it iterates until the end of the iterator and returns `true`. If `every()` returns `false`, the underlying iterator is closed by calling its `return()` method. The main advantage of iterator helpers over array methods is their ability to work with infinite iterators. With infinite iterators, `every()` returns `false` as soon as the first falsy value is found. If the `callbackFn` always returns a truthy value, the method never returns. ## Examples ### Using every() ```js function* fibonacci() { let current = 1; let next = 1; while (true) { yield current; [current, next] = [next, current + next]; } } const isEven = (x) => x % 2 === 0; console.log(fibonacci().every(isEven)); // false const isPositive = (x) => x > 0; console.log(fibonacci().take(10).every(isPositive)); // true console.log(fibonacci().every(isPositive)); // Never completes ``` Calling `every()` always closes the underlying iterator, even if the method early-returns. The iterator is never left in a half-way state. ```js const seq = fibonacci(); console.log(seq.every(isEven)); // false console.log(seq.next()); // { value: undefined, done: true } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Iterator.prototype.every` in `core-js`](https://github.com/zloirock/core-js#iterator-helpers) - {{jsxref("Iterator")}} - {{jsxref("Iterator.prototype.find()")}} - {{jsxref("Iterator.prototype.some()")}} - {{jsxref("Array.prototype.every()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator/iterator/index.md
--- title: Iterator() constructor slug: Web/JavaScript/Reference/Global_Objects/Iterator/Iterator page-type: javascript-constructor status: - experimental browser-compat: javascript.builtins.Iterator.Iterator --- {{JSRef}}{{SeeCompatTable}} The **`Iterator()`** constructor is intended to be used as the [superclass](/en-US/docs/Web/JavaScript/Reference/Classes/extends) of other classes that create iterators. It throws an error when constructed by itself. ## Syntax ```js-nolint new Iterator() ``` > **Note:** `Iterator()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}. In addition, `Iterator()` cannot actually be constructed itself — it's usually implicitly constructed through [`super()`](/en-US/docs/Web/JavaScript/Reference/Operators/super) calls inside the constructor of a subclass. ### Parameters None. ### Return value A new {{jsxref("Iterator")}} object. ### Exceptions - {{jsxref("TypeError")}} - : When [`new.target`](/en-US/docs/Web/JavaScript/Reference/Operators/new.target) is the `Iterator` function itself, i.e. when the `Iterator` constructor itself is constructed. ## Description `Iterator` represents an _abstract class_ — a class that provides common utilities for its subclasses, but is not intended to be instantiated itself. It is the superclass of all other iterator classes, and is used to create subclasses that implement specific iteration algorithms — namely, all subclasses of `Iterator` must implement a `next()` method as required by the [iterator protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol). Because `Iterator` doesn't actually provide the `next()` method, it doesn't make sense to construct an `Iterator` directly. You can also use {{jsxref("Iterator.from()")}} to create an `Iterator` instance from an existing iterable or iterator object. ## Examples ### Subclassing Iterator The following example defines a custom data structure, `Range`, which allows iteration. The simplest way to make an object iterable is to provide an [`[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator) method in the form of a generator function: ```js class Range { #start; #end; #step; constructor(start, end, step = 1) { this.#start = start; this.#end = end; this.#step = step; } *[Symbol.iterator]() { for (let value = this.#start; value <= this.#end; value += this.#step) { yield value; } } } const range = new Range(1, 5); for (const num of range) { console.log(num); } ``` This works, but it isn't as nice as how built-in iterators work. There are two problems: - The returned iterator inherits from {{jsxref("Generator")}}, which means modifications to `Generator.prototype` are going to affect the returned iterator, which is a leak of abstraction. - The returned iterator does not inherit from a custom prototype, which makes it harder if we intend to add extra methods to the iterator. We can mimic the implementation of built-in iterators, such as [map iterators](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/@@iterator), by subclassing `Iterator`. This enables us to define extra properties, such as [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag), while making the iterator helper methods available on the returned iterator. ```js class Range { #start; #end; #step; constructor(start, end, step = 1) { this.#start = start; this.#end = end; this.#step = step; } static #RangeIterator = class extends Iterator { #cur; #s; #e; constructor(range) { super(); this.#cur = range.#start; this.#s = range.#step; this.#e = range.#end; } static { Object.defineProperty(this.prototype, Symbol.toStringTag, { value: "Range Iterator", configurable: true, enumerable: false, writable: false, }); // Avoid #RangeIterator from being accessible outside delete this.prototype.constructor; } next() { if (this.#cur > this.#e) { return { value: undefined, done: true }; } const res = { value: this.#cur, done: false }; this.#cur += this.#s; return res; } }; [Symbol.iterator]() { return new Range.#RangeIterator(this); } } const range = new Range(1, 5); for (const num of range) { console.log(num); } ``` The subclassing pattern is useful if you want to create many custom iterators. If you have an existing iterable or iterator object which doesn't inherit from `Iterator`, and you just want to call iterator helper methods on it, you can use {{jsxref("Iterator.from()")}} to create a one-time `Iterator` instance. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Iterator` in `core-js`](https://github.com/zloirock/core-js#iterator-helpers) - {{jsxref("Iterator")}} - {{jsxref("Iterator.from()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator/toarray/index.md
--- title: Iterator.prototype.toArray() slug: Web/JavaScript/Reference/Global_Objects/Iterator/toArray page-type: javascript-instance-method status: - experimental browser-compat: javascript.builtins.Iterator.toArray --- {{JSRef}}{{SeeCompatTable}} The **`toArray()`** method of {{jsxref("Iterator")}} instances creates a new {{jsxref("Array")}} instance populated with the elements yielded from the iterator. ## Syntax ```js-nolint toArray() ``` ### Parameters None. ### Return value A new {{jsxref("Array")}} instance containing the elements from the iterator in the order they were produced. ## Examples ### Using toArray() `iterator.toArray()` is equivalent to `Array.from(iterator)` and `[...iterator]`, except that it's easier to chain when multiple iterator helper methods are involved. The following example creates an iterator that yields terms in the Fibonacci sequence, takes the first 10 terms, filters out the odd numbers, and converts the result to an array: ```js function* fibonacci() { let current = 1; let next = 1; while (true) { yield current; [current, next] = [next, current + next]; } } const array = fibonacci() .take(10) .filter((x) => x % 2 === 0) .toArray(); console.log(array); // [2, 8, 34] ``` Note that it's a good idea to call `toArray()` as a last step of your processing. For example, `fibonacci().take(10).toArray().filter(...)` is less efficient, because iterator helpers are lazy and avoids creating a temporary array. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Iterator.prototype.toArray` in `core-js`](https://github.com/zloirock/core-js#iterator-helpers) - {{jsxref("Iterator")}} - {{jsxref("Array.from()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator/reduce/index.md
--- title: Iterator.prototype.reduce() slug: Web/JavaScript/Reference/Global_Objects/Iterator/reduce page-type: javascript-instance-method status: - experimental browser-compat: javascript.builtins.Iterator.reduce --- {{JSRef}}{{SeeCompatTable}} The **`reduce()`** method of {{jsxref("Iterator")}} instances is similar to {{jsxref("Array.prototype.reduce")}}: it executes a user-supplied "reducer" callback function on each element produced by the iterator, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements is a single value. ## Syntax ```js-nolint reduce(callbackFn) reduce(callbackFn, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element produced by the iterator. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments: - `accumulator` - : The value resulting from the previous call to `callbackFn`. On the first call, its value is `initialValue` if the latter is specified; otherwise its value is the first element of the iterator. - `currentValue` - : The value of the current element. On the first call, its value is the first element of the iterator if `initialValue` is specified; otherwise its value is the second element. - `currentIndex` - : The index position of `currentValue`. On the first call, its value is `0` if `initialValue` is specified, otherwise `1`. - `initialValue` {{optional_inline}} - : A value to which `accumulator` is initialized the first time the callback is called. If `initialValue` is specified, `callbackFn` starts executing with the first element as `currentValue`. If `initialValue` is _not_ specified, `accumulator` is initialized to the first element, and `callbackFn` starts executing with the second element as `currentValue`. In this case, if the iterator is empty (so that there's no first value to return as `accumulator`), an error is thrown. ### Return value The value that results from running the "reducer" callback function to completion over the entire iterator. ### Exceptions - {{jsxref("TypeError")}} - : Thrown if the iterator contains no elements and `initialValue` is not provided. ## Description See {{jsxref("Array.prototype.reduce()")}} for details about how `reduce()` works. Unlike most other iterator helper methods, it does not work well with infinite iterators, because it is not lazy. ## Examples ### Using reduce() The following example creates an iterator that yields terms in the Fibonacci sequence, and then sums the first ten terms: ```js function* fibonacci() { let current = 1; let next = 1; while (true) { yield current; [current, next] = [next, current + next]; } } console.log( fibonacci() .take(10) .reduce((a, b) => a + b), ); // 143 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Iterator.prototype.reduce` in `core-js`](https://github.com/zloirock/core-js#iterator-helpers) - {{jsxref("Iterator")}} - {{jsxref("Iterator.prototype.map()")}} - {{jsxref("Iterator.prototype.flatMap()")}} - {{jsxref("Array.prototype.reduce()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator/@@iterator/index.md
--- title: Iterator.prototype[@@iterator]() slug: Web/JavaScript/Reference/Global_Objects/Iterator/@@iterator page-type: javascript-instance-method browser-compat: javascript.builtins.Iterator.@@iterator --- {{JSRef}} The **`[@@iterator]()`** method of {{jsxref("Iterator")}} instances implements the [iterable protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) and allows built-in iterators to be consumed by most syntaxes expecting iterables, such as the [spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and {{jsxref("Statements/for...of", "for...of")}} loops. It returns the value of [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this), which is the iterator object itself. ## Syntax ```js-nolint iterator[Symbol.iterator]() ``` ### Parameters None. ### Return value The value of [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this), which is the iterator object itself. ## Examples ### Iteration using for...of loop Note that you seldom need to call this method directly. The existence of the `@@iterator` method makes built-in iterators [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol), and iterating syntaxes like the `for...of` loop automatically call this method to obtain the iterator to loop over. ```js const arrIterator = [1, 2, 3].values(); for (const value of arrIterator) { console.log(value); } // Logs: 1, 2, 3 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Iterator")}} - {{jsxref("Symbol.iterator")}} - [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator/some/index.md
--- title: Iterator.prototype.some() slug: Web/JavaScript/Reference/Global_Objects/Iterator/some page-type: javascript-instance-method status: - experimental browser-compat: javascript.builtins.Iterator.some --- {{JSRef}}{{SeeCompatTable}} The **`some()`** method of {{jsxref("Iterator")}} instances is similar to {{jsxref("Array.prototype.some()")}}: it tests whether at least one element produced by the iterator passes the test implemented by the provided function. It returns a boolean value. ## Syntax ```js-nolint some(callbackFn) ``` ### Parameters - `callbackFn` - : A function to execute for each element produced by the iterator. It should return a [truthy](/en-US/docs/Glossary/Truthy) value to indicate the element passes the test, and a [falsy](/en-US/docs/Glossary/Falsy) value otherwise. The function is called with the following arguments: - `element` - : The current element being processed. - `index` - : The index of the current element being processed. ### Return value `true` if the callback function returns a {{Glossary("truthy")}} value for at least one element. Otherwise, `false`. ## Description `some()` iterates the iterator and invokes the `callbackFn` function once for each element. It returns `true` immediately if the callback function returns a truthy value. Otherwise, it iterates until the end of the iterator and returns `false`. If `some()` returns `true`, the underlying iterator is closed by calling its `return()` method. The main advantage of iterator helpers over array methods is their ability to work with infinite iterators. With infinite iterators, `some()` returns `true` as soon as the first truthy value is found. If the `callbackFn` always returns a falsy value, the method never returns. ## Examples ### Using some() ```js function* fibonacci() { let current = 1; let next = 1; while (true) { yield current; [current, next] = [next, current + next]; } } const isEven = (x) => x % 2 === 0; console.log(fibonacci().some(isEven)); // true const isNegative = (x) => x < 0; const isPositive = (x) => x > 0; console.log(fibonacci().take(10).some(isPositive)); // false console.log(fibonacci().some(isNegative)); // Never completes ``` Calling `some()` always closes the underlying iterator, even if the method early-returns. The iterator is never left in a half-way state. ```js const seq = fibonacci(); console.log(seq.some(isEven)); // true console.log(seq.next()); // { value: undefined, done: true } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Iterator.prototype.some` in `core-js`](https://github.com/zloirock/core-js#iterator-helpers) - {{jsxref("Iterator")}} - {{jsxref("Iterator.prototype.every()")}} - {{jsxref("Iterator.prototype.find()")}} - {{jsxref("Array.prototype.some()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator/foreach/index.md
--- title: Iterator.prototype.forEach() slug: Web/JavaScript/Reference/Global_Objects/Iterator/forEach page-type: javascript-instance-method status: - experimental browser-compat: javascript.builtins.Iterator.forEach --- {{JSRef}}{{SeeCompatTable}} The **`forEach()`** method of {{jsxref("Iterator")}} instances is similar to {{jsxref("Array.prototype.forEach()")}}: it executes a provided function once for each element produced by the iterator. ## Syntax ```js-nolint forEach(callbackFn) ``` ### Parameters - `callbackFn` - : A function to execute for each element produced by the iterator. Its return value is discarded. The function is called with the following arguments: - `element` - : The current element being processed. - `index` - : The index of the current element being processed. ### Return value {{jsxref("undefined")}}. ## Description `forEach()` iterates the iterator and invokes the `callbackFn` function once for each element. Unlike most other iterator helper methods, it does not work well with infinite iterators, because it is not lazy. ## Examples ### Using forEach() ```js new Set([1, 2, 3]).values().forEach((v) => console.log(v)); // Logs: // 1 // 2 // 3 ``` This is equivalent to: ```js for (const v of new Set([1, 2, 3]).values()) { console.log(v); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Iterator.prototype.forEach` in `core-js`](https://github.com/zloirock/core-js#iterator-helpers) - {{jsxref("Iterator")}} - {{jsxref("Iterator.prototype.find()")}} - {{jsxref("Iterator.prototype.map()")}} - {{jsxref("Iterator.prototype.filter()")}} - {{jsxref("Iterator.prototype.every()")}} - {{jsxref("Iterator.prototype.some()")}} - {{jsxref("Array.prototype.forEach()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator/drop/index.md
--- title: Iterator.prototype.drop() slug: Web/JavaScript/Reference/Global_Objects/Iterator/drop page-type: javascript-instance-method status: - experimental browser-compat: javascript.builtins.Iterator.drop --- {{JSRef}}{{SeeCompatTable}} The **`drop()`** method of {{jsxref("Iterator")}} instances returns a new [iterator helper](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator#iterator_helpers) that skips the given number of elements at the start of this iterator. ## Syntax ```js-nolint drop(limit) ``` ### Parameters - `limit` - : The number of elements to drop from the start of the iteration. ### Return value A new [iterator helper](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator#iterator_helpers). The first time the returned iterator helper's `next()` method is called, the current iterator is immediately advanced by `limit` elements, and then the next element (the `limit+1`-th element) is yielded. The iterator helper then yields the remaining elements one-by-one. If the current iterator has fewer than `limit` elements, the new iterator helper will be immediately completed the first time `next()` is called. ### Exceptions - {{jsxref("RangeError")}} - : Thrown if `limit` becomes {{jsxref("NaN")}} or negative when [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). ## Examples ### Using drop() The following example creates an iterator that yields terms in the Fibonacci sequence, starting from the 3rd term by dropping the first two terms: ```js function* fibonacci() { let current = 1; let next = 1; while (true) { yield current; [current, next] = [next, current + next]; } } const seq = fibonacci().drop(2); console.log(seq.next().value); // 2 console.log(seq.next().value); // 3 ``` This is equivalent to: ```js const seq = fibonacci(); seq.next(); seq.next(); ``` ### Using drop() with a for...of loop `drop()` is most convenient when you are not hand-rolling the iterator. Because iterators are also iterable, you can iterate the returned helper with a {{jsxref("Statements/for...of", "for...of")}} loop: ```js for (const n of fibonacci().drop(2)) { console.log(n); if (n > 30) { break; } } // Logs: // 2 // 3 // 5 // 8 // 13 // 21 // 34 ``` ### Combining drop() with take() You can combine `drop()` with {{jsxref("Iterator.prototype.take()")}} to get a slice of an iterator: ```js for (const n of fibonacci().drop(2).take(5)) { // Drops the first two elements, then takes the next five console.log(n); } // Logs: // 2 // 3 // 5 // 8 // 13 for (const n of fibonacci().take(5).drop(2)) { // Takes the first five elements, then drops the first two console.log(n); } // Logs: // 2 // 3 // 5 ``` ### Lower and upper bounds of drop count When the `limit` is negative or {{jsxref("NaN")}}, a {{jsxref("RangeError")}} is thrown: ```js fibonacci().drop(-1); // RangeError: -1 must be positive fibonacci().drop(undefined); // RangeError: undefined must be positive ``` When the `limit` is larger than the total number of elements the iterator can produce (such as {{jsxref("Infinity")}}), the returned iterator helper will instantly drop all elements and then be completed the first time `next()` is called. If the current iterator is infinite, the returned iterator helper will never complete. ```js fibonacci().drop(Infinity).next(); // Never ends new Set([1, 2, 3]).values().drop(Infinity).next(); // { value: undefined, done: true } new Set([1, 2, 3]).values().drop(4).next(); // { value: undefined, done: true } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Iterator.prototype.drop` in `core-js`](https://github.com/zloirock/core-js#iterator-helpers) - {{jsxref("Iterator")}} - {{jsxref("Iterator.prototype.take()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator
data/mdn-content/files/en-us/web/javascript/reference/global_objects/iterator/filter/index.md
--- title: Iterator.prototype.filter() slug: Web/JavaScript/Reference/Global_Objects/Iterator/filter page-type: javascript-instance-method status: - experimental browser-compat: javascript.builtins.Iterator.filter --- {{JSRef}}{{SeeCompatTable}} The **`filter()`** method of {{jsxref("Iterator")}} instances returns a new [iterator helper](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator#iterator_helpers) that yields only those elements of the iterator for which the provided callback function returns `true`. ## Syntax ```js-nolint filter(callbackFn) ``` ### Parameters - `callbackFn` - : A function to execute for each element produced by the iterator. It should return a [truthy](/en-US/docs/Glossary/Truthy) value to make the element yielded by the iterator helper, and a [falsy](/en-US/docs/Glossary/Falsy) value otherwise. The function is called with the following arguments: - `element` - : The current element being processed. - `index` - : The index of the current element being processed. ### Return value A new [iterator helper](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator#iterator_helpers). Each time the iterator helper's `next()` method is called, it returns the next element in the iterator for which the callback function returns `true`. When the underlying iterator is completed, the iterator helper is also completed (the `next()` method produces `{ value: undefined, done: true }`). ## Description The main advantage of iterator helpers over array methods is their ability to work with infinite iterators. With infinite iterators, `filter()` allows you to iterate over only those elements that satisfy a given condition. ## Examples ### Using filter() The following example creates an iterator that yields terms in the Fibonacci sequence, and then reads the first few terms that are even: ```js function* fibonacci() { let current = 1; let next = 1; while (true) { yield current; [current, next] = [next, current + next]; } } const seq = fibonacci().filter((x) => x % 2 === 0); console.log(seq.next().value); // 2 console.log(seq.next().value); // 8 console.log(seq.next().value); // 34 ``` ### Using filter() with a for...of loop `filter()` is most convenient when you are not hand-rolling the iterator. Because iterators are also iterable, you can iterate the returned helper with a {{jsxref("Statements/for...of", "for...of")}} loop: ```js for (const n of fibonacci().filter((x) => x % 2 === 0)) { console.log(n); if (n > 30) { break; } } // Logs: // 2 // 8 // 34 ``` This is equivalent to: ```js for (const n of fibonacci()) { if (n % 2 !== 0) { continue; } console.log(n); if (n > 30) { break; } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Iterator.prototype.filter` in `core-js`](https://github.com/zloirock/core-js#iterator-helpers) - {{jsxref("Iterator")}} - {{jsxref("Iterator.prototype.forEach()")}} - {{jsxref("Iterator.prototype.every()")}} - {{jsxref("Iterator.prototype.map()")}} - {{jsxref("Iterator.prototype.some()")}} - {{jsxref("Iterator.prototype.reduce()")}} - {{jsxref("Array.prototype.filter()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/eval/index.md
--- title: eval() slug: Web/JavaScript/Reference/Global_Objects/eval page-type: javascript-function browser-compat: javascript.builtins.eval --- {{jsSidebar("Objects")}} > **Warning:** Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use `eval()`. See [Never use eval()!](#never_use_eval!), below. The **`eval()`** function evaluates JavaScript code represented as a string and returns its completion value. The source is parsed as a script. {{EmbedInteractiveExample("pages/js/globalprops-eval.html")}} ## Syntax ```js-nolint eval(script) ``` ### Parameters - `script` - : A string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects. It will be parsed as a script, so [`import`](/en-US/docs/Web/JavaScript/Reference/Statements/import) declarations (which can only exist in modules) are not allowed. ### Return value The completion value of evaluating the given code. If the completion value is empty, {{jsxref("undefined")}} is returned. If `script` is not a string primitive, `eval()` returns the argument unchanged. ### Exceptions Throws any exception that occurs during evaluation of the code, including {{jsxref("SyntaxError")}} if `script` fails to be parsed as a script. ## Description `eval()` is a function property of the global object. The argument of the `eval()` function is a string. It will evaluate the source string as a script body, which means both statements and expressions are allowed. It returns the completion value of the code. For expressions, it's the value the expression evaluates to. Many statements and declarations have completion values as well, but the result may be surprising (for example, the completion value of an assignment is the assigned value, but the completion value of [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let) is undefined), so it's recommended to not rely on statements' completion values. In strict mode, declaring a variable named `eval` or re-assigning `eval` is a {{jsxref("SyntaxError")}}. ```js-nolint example-bad "use strict"; const eval = 1; // SyntaxError: Unexpected eval or arguments in strict mode ``` If the argument of `eval()` is not a string, `eval()` returns the argument unchanged. In the following example, passing a `String` object instead of a primitive causes `eval()` to return the `String` object rather than evaluating the string. ```js eval(new String("2 + 2")); // returns a String object containing "2 + 2" eval("2 + 2"); // returns 4 ``` To work around the issue in a generic fashion, you can [coerce the argument to a string](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) yourself before passing it to `eval()`. ```js const expression = new String("2 + 2"); eval(String(expression)); // returns 4 ``` ### Direct and indirect eval There are two modes of `eval()` calls: _direct_ eval and _indirect_ eval. Direct eval, as the name implies, refers to _directly_ calling the global `eval` function with `eval(...)`. Everything else, including invoking it via an aliased variable, via a member access or other expression, or through the optional chaining [`?.`](/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) operator, is indirect. ```js // Direct call eval("x + y"); // Indirect call using the comma operator to return eval (0, eval)("x + y"); // Indirect call through optional chaining eval?.("x + y"); // Indirect call using a variable to store and return eval const geval = eval; geval("x + y"); // Indirect call through member access const obj = { eval }; obj.eval("x + y"); ``` Indirect eval can be seen as if the code is evaluated within a separate `<script>` tag. This means: - Indirect eval works in the global scope rather than the local scope, and the code being evaluated doesn't have access to local variables within the scope where it's being called. ```js function test() { const x = 2; const y = 4; // Direct call, uses local scope console.log(eval("x + y")); // Result is 6 console.log(eval?.("x + y")); // Uses global scope, throws because x is undefined } ``` - Indirect `eval` would not inherit the strictness of the surrounding context, and would only be in [strict mode](/en-US/docs/Web/JavaScript/Reference/Strict_mode) if the source string itself has a `"use strict"` directive. ```js function strictContext() { "use strict"; eval?.(`with (Math) console.log(PI);`); } function strictContextStrictEval() { "use strict"; eval?.(`"use strict"; with (Math) console.log(PI);`); } strictContext(); // Logs 3.141592653589793 strictContextStrictEval(); // Throws a SyntaxError because the source string is in strict mode ``` On the other hand, direct eval inherits the strictness of the invoking context. ```js function nonStrictContext() { eval(`with (Math) console.log(PI);`); } function strictContext() { "use strict"; eval(`with (Math) console.log(PI);`); } nonStrictContext(); // Logs 3.141592653589793 strictContext(); // Throws a SyntaxError because it's in strict mode ``` - `var`-declared variables and [function declarations](/en-US/docs/Web/JavaScript/Reference/Statements/function) would go into the surrounding scope if the source string is not interpreted in strict mode — for indirect eval, they become global variables. If it's a direct eval in a strict mode context, or if the `eval` source string itself is in strict mode, then `var` and function declarations do not "leak" into the surrounding scope. ```js // Neither context nor source string is strict, // so var creates a variable in the surrounding scope eval("var a = 1;"); console.log(a); // 1 // Context is not strict, but eval source is strict, // so b is scoped to the evaluated script eval("'use strict'; var b = 1;"); console.log(b); // ReferenceError: b is not defined function strictContext() { "use strict"; // Context is strict, but this is indirect and the source // string is not strict, so c is still global eval?.("var c = 1;"); // Direct eval in a strict context, so d is scoped eval("var d = 1;"); } strictContext(); console.log(c); // 1 console.log(d); // ReferenceError: d is not defined ``` [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let) and [`const`](/en-US/docs/Web/JavaScript/Reference/Statements/const) declarations within the evaluated string are always scoped to that script. - Direct eval may have access to additional contextual expressions. For example, in a function's body, one can use [`new.target`](/en-US/docs/Web/JavaScript/Reference/Operators/new.target): ```js function Ctor() { eval("console.log(new.target)"); } new Ctor(); // [Function: Ctor] ``` ### Never use eval()! Using direct `eval()` suffers from multiple problems: - `eval()` executes the code it's passed with the privileges of the caller. If you run `eval()` with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, allowing third-party code to access the scope in which `eval()` was invoked (if it's a direct eval) can lead to possible attacks that reads or changes local variables. - `eval()` is slower than the alternatives, since it has to invoke the JavaScript interpreter, while many other constructs are optimized by modern JS engines. - Modern JavaScript interpreters convert JavaScript to machine code. This means that any concept of variable naming gets obliterated. Thus, any use of `eval()` will force the browser to do long expensive variable name lookups to figure out where the variable exists in the machine code and set its value. Additionally, new things can be introduced to that variable through `eval()`, such as changing the type of that variable, forcing the browser to re-evaluate all of the generated machine code to compensate. - Minifiers give up on any minification if the scope is transitively depended on by `eval()`, because otherwise `eval()` cannot read the correct variable at runtime. There are many cases where the use of `eval()` or related methods can be optimized or avoided altogether. #### Using indirect eval() Consider this code: ```js function looseJsonParse(obj) { return eval(`(${obj})`); } console.log(looseJsonParse("{ a: 4 - 1, b: function () {}, c: new Date() }")); ``` Simply using indirect eval and forcing strict mode can make the code much better: ```js function looseJsonParse(obj) { return eval?.(`"use strict";(${obj})`); } console.log(looseJsonParse("{ a: 4 - 1, b: function () {}, c: new Date() }")); ``` The two code snippets above may seem to work the same way, but they do not; the first one using direct eval suffers from multiple problems. - It is a great deal slower, due to more scope inspections. Notice `c: new Date()` in the evaluated string. In the indirect eval version, the object is being evaluated in the global scope, so it is safe for the interpreter to assume that `Date` refers to the global `Date()` constructor instead of a local variable called `Date`. However, in the code using direct eval, the interpreter cannot assume this. For example, in the following code, `Date` in the evaluated string doesn't refer to `window.Date()`. ```js function looseJsonParse(obj) { function Date() {} return eval(`(${obj})`); } console.log(looseJsonParse(`{ a: 4 - 1, b: function () {}, c: new Date() }`)); ``` Thus, in the `eval()` version of the code, the browser is forced to make the expensive lookup call to check to see if there are any local variables called `Date()`. - If not using strict mode, `var` declarations within the `eval()` source becomes variables in the surrounding scope. This leads to hard-to-debug issues if the string is acquired from external input, especially if there's an existing variable with the same name. - Direct eval can read and mutate bindings in the surrounding scope, which may lead to external input corrupting local data. - When using direct `eval`, especially when the eval source cannot be proven to be in strict mode, the engine — and build tools — have to disable all optimizations related to inlining, because the `eval()` source can depend on any variable name in its surrounding scope. However, using indirect `eval()` does not allow passing extra bindings other than existing global variables for the evaluated source to read. If you need to specify additional variables that the evaluated source should have access to, consider using the `Function()` constructor. #### Using the Function() constructor The [`Function()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) constructor is very similar to the indirect eval example above: it also evaluates the JavaScript source passed to it in the global scope without reading or mutating any local bindings, and therefore allows engines to do more optimizations than direct `eval()`. The difference between `eval()` and `Function()` is that the source string passed to `Function()` is parsed as a function body, not as a script. There are a few nuances — for example, you can use `return` statements at the top level of a function body, but not in a script. The `Function()` constructor is useful if you wish to create local bindings within your eval source, by passing the variables as parameter bindings. ```js function Date(n) { return [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", ][n % 7 || 0]; } function runCodeWithDateFunction(obj) { return Function("Date", `"use strict";return (${obj});`)(Date); } console.log(runCodeWithDateFunction("Date(5)")); // Saturday ``` Both `eval()` and `Function()` implicitly evaluate arbitrary code, and are forbidden in strict [CSP](/en-US/docs/Web/HTTP/CSP) settings. There are also additional safer (and faster!) alternatives to `eval()` or `Function()` for common use-cases. #### Using bracket accessors You should not use `eval()` to access properties dynamically. Consider the following example where the property of the object to be accessed is not known until the code is executed. This can be done with `eval()`: ```js const obj = { a: 20, b: 30 }; const propName = getPropName(); // returns "a" or "b" const result = eval(`obj.${propName}`); ``` However, `eval()` is not necessary here — in fact, it's more error-prone, because if `propName` is not a valid identifier, it leads to a syntax error. Moreover, if `getPropName` is not a function you control, this may lead to execution of arbitrary code. Instead, use the [property accessors](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors), which are much faster and safer: ```js const obj = { a: 20, b: 30 }; const propName = getPropName(); // returns "a" or "b" const result = obj[propName]; // obj["a"] is the same as obj.a ``` You can even use this method to access descendant properties. Using `eval()`, this would look like: ```js const obj = { a: { b: { c: 0 } } }; const propPath = getPropPath(); // suppose it returns "a.b.c" const result = eval(`obj.${propPath}`); // 0 ``` Avoiding `eval()` here could be done by splitting the property path and looping through the different properties: ```js function getDescendantProp(obj, desc) { const arr = desc.split("."); while (arr.length) { obj = obj[arr.shift()]; } return obj; } const obj = { a: { b: { c: 0 } } }; const propPath = getPropPath(); // suppose it returns "a.b.c" const result = getDescendantProp(obj, propPath); // 0 ``` Setting a property that way works similarly: ```js function setDescendantProp(obj, desc, value) { const arr = desc.split("."); while (arr.length > 1) { obj = obj[arr.shift()]; } return (obj[arr[0]] = value); } const obj = { a: { b: { c: 0 } } }; const propPath = getPropPath(); // suppose it returns "a.b.c" const result = setDescendantProp(obj, propPath, 1); // obj.a.b.c is now 1 ``` However, beware that using bracket accessors with unconstrained input is not safe either — it may lead to [object injection attacks](https://github.com/nodesecurity/eslint-plugin-security/blob/main/docs/the-dangers-of-square-bracket-notation.md). #### Using callbacks JavaScript has [first-class functions](/en-US/docs/Glossary/First-class_Function), which means you can pass functions as arguments to other APIs, store them in variables and objects' properties, and so on. Many DOM APIs are designed with this in mind, so you can (and should) write: ```js // Instead of setTimeout("…", 1000) use: setTimeout(() => { // … }, 1000); // Instead of elt.setAttribute("onclick", "…") use: elt.addEventListener("click", () => { // … }); ``` [Closures](/en-US/docs/Web/JavaScript/Closures) are also helpful as a way to create parameterized functions without concatenating strings. #### Using JSON If the string you're calling `eval()` on contains data (for example, an array: `"[1, 2, 3]"`), as opposed to code, you should consider switching to {{Glossary("JSON")}}, which allows the string to use a subset of JavaScript syntax to represent data. Note that since JSON syntax is limited compared to JavaScript syntax, many valid JavaScript literals will not parse as JSON. For example, trailing commas are not allowed in JSON, and property names (keys) in object literals must be enclosed in quotes. Be sure to use a JSON serializer to generate strings that will be later parsed as JSON. Passing carefully constrained data instead of arbitrary code is a good idea in general. For example, an extension designed to scrape contents of web-pages could have the scraping rules defined in [XPath](/en-US/docs/Web/XPath) instead of JavaScript code. ## Examples ### Using eval() In the following code, both of the statements containing `eval()` return 42. The first evaluates the string `"x + y + 1"`; the second evaluates the string `"42"`. ```js const x = 2; const y = 39; const z = "42"; eval("x + y + 1"); // 42 eval(z); // 42 ``` ### eval() returns the completion value of statements `eval()` returns the completion value of statements. For `if`, it would be the last expression or statement evaluated. ```js const str = "if (a) { 1 + 1 } else { 1 + 2 }"; let a = true; let b = eval(str); console.log(`b is: ${b}`); // b is: 2 a = false; b = eval(str); console.log(`b is: ${b}`); // b is: 3 ``` The following example uses `eval()` to evaluate the string `str`. This string consists of JavaScript statements that assign `z` a value of 42 if `x` is five, and assign 0 to `z` otherwise. When the second statement is executed, `eval()` will cause these statements to be performed, and it will also evaluate the set of statements and return the value that is assigned to `z`, because the completion value of an assignment is the assigned value. ```js const x = 5; const str = `if (x === 5) { console.log("z is 42"); z = 42; } else { z = 0; }`; console.log("z is ", eval(str)); // z is 42 z is 42 ``` If you assign multiple values then the last value is returned. ```js let x = 5; const str = `if (x === 5) { console.log("z is 42"); z = 42; x = 420; } else { z = 0; }`; console.log("x is", eval(str)); // z is 42 x is 420 ``` ### eval() as a string defining function requires "(" and ")" as prefix and suffix ```js // This is a function declaration const fctStr1 = "function a() {}"; // This is a function expression const fctStr2 = "(function b() {})"; const fct1 = eval(fctStr1); // return undefined, but `a` is available as a global function now const fct2 = eval(fctStr2); // return the function `b` ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Property accessors](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors) - [WebExtensions: Using eval in content scripts](/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#using_eval_in_content_scripts)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/encodeuri/index.md
--- title: encodeURI() slug: Web/JavaScript/Reference/Global_Objects/encodeURI page-type: javascript-function browser-compat: javascript.builtins.encodeURI --- {{jsSidebar("Objects")}} The **`encodeURI()`** function encodes a {{Glossary("URI")}} by replacing each instance of certain characters by one, two, three, or four escape sequences representing the {{Glossary("UTF-8")}} encoding of the character (will only be four escape sequences for characters composed of two surrogate characters). Compared to {{jsxref("encodeURIComponent()")}}, this function encodes fewer characters, preserving those that are part of the URI syntax. {{EmbedInteractiveExample("pages/js/globalprops-encodeuri.html")}} ## Syntax ```js-nolint encodeURI(uri) ``` ### Parameters - `uri` - : A string to be encoded as a URI. ### Return value A new string representing the provided string encoded as a URI. ### Exceptions - {{jsxref("URIError")}} - : Thrown if `uri` contains a [lone surrogate](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#utf-16_characters_unicode_code_points_and_grapheme_clusters). ## Description `encodeURI()` is a function property of the global object. The `encodeURI()` function escapes characters by UTF-8 code units, with each octet encoded in the format `%XX`, left-padded with 0 if necessary. Because lone surrogates in UTF-16 do not encode any valid Unicode character, they cause `encodeURI()` to throw a {{jsxref("URIError")}}. `encodeURI()` escapes all characters **except**: ```plain A–Z a–z 0–9 - _ . ! ~ * ' ( ) ; / ? : @ & = + $ , # ``` The characters on the second line are characters that may be part of the URI syntax, and are only escaped by `encodeURIComponent()`. Both `encodeURI()` and `encodeURIComponent()` do not encode the characters `-.!~*'()`, known as "unreserved marks", which do not have a reserved purpose but are allowed in a URI "as is". (See [RFC2396](https://www.ietf.org/rfc/rfc2396.txt)) The `encodeURI()` function does not encode characters that have special meaning (reserved characters) for a URI. The following example shows all the parts that a URI can possibly contain. Note how certain characters are used to signify special meaning: ```url http://username:[email protected]:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor ``` `encodeURI`, as the name implies, is used to encode a URL as a whole, assuming it is already well-formed. If you want to dynamically assemble string values into a URL, you probably want to use {{jsxref("encodeURIComponent()")}} on each dynamic segment instead, to avoid URL syntax characters in unwanted places. ```js const name = "Ben & Jerry's"; // This is bad: const link = encodeURI(`https://example.com/?choice=${name}`); // "https://example.com/?choice=Ben%20&%20Jerry's" console.log([...new URL(link).searchParams]); // [['choice', 'Ben '], [" Jerry's", ''] // Instead: const link = encodeURI( `https://example.com/?choice=${encodeURIComponent(name)}`, ); // "https://example.com/?choice=Ben%2520%2526%2520Jerry's" console.log([...new URL(link).searchParams]); // [['choice', "Ben%20%26%20Jerry's"]] ``` ## Examples ### encodeURI() vs. encodeURIComponent() `encodeURI()` differs from {{jsxref("encodeURIComponent()")}} as follows: ```js const set1 = ";/?:@&=+$,#"; // Reserved Characters const set2 = "-.!~*'()"; // Unreserved Marks const set3 = "ABC abc 123"; // Alphanumeric Characters + Space console.log(encodeURI(set1)); // ;/?:@&=+$,# console.log(encodeURI(set2)); // -.!~*'() console.log(encodeURI(set3)); // ABC%20abc%20123 (the space gets encoded as %20) console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24%23 console.log(encodeURIComponent(set2)); // -.!~*'() console.log(encodeURIComponent(set3)); // ABC%20abc%20123 (the space gets encoded as %20) ``` ### Encoding a lone surrogate throws A {{jsxref("URIError")}} will be thrown if one attempts to encode a surrogate which is not part of a high-low pair. For example: ```js // High-low pair OK encodeURI("\uD800\uDFFF"); // "%F0%90%8F%BF" // Lone high-surrogate code unit throws "URIError: malformed URI sequence" encodeURI("\uD800"); // Lone low-surrogate code unit throws "URIError: malformed URI sequence" encodeURI("\uDFFF"); ``` You can use {{jsxref("String.prototype.toWellFormed()")}}, which replaces lone surrogates with the Unicode replacement character (U+FFFD), to avoid this error. You can also use {{jsxref("String.prototype.isWellFormed()")}} to check if a string contains lone surrogates before passing it to `encodeURI()`. ### Encoding for RFC3986 The more recent [RFC3986](https://datatracker.ietf.org/doc/html/rfc3986) makes square brackets reserved (for {{Glossary("IPv6")}}) and thus not encoded when forming something which could be part of a URL (such as a host). It also reserves !, ', (, ), and \*, even though these characters have no formalized URI delimiting uses. The following function encodes a string for RFC3986-compliant URL format. ```js function encodeRFC3986URI(str) { return encodeURI(str) .replace(/%5B/g, "[") .replace(/%5D/g, "]") .replace( /[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, ); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("decodeURI()")}} - {{jsxref("encodeURIComponent()")}} - {{jsxref("decodeURIComponent()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number/index.md
--- title: Number slug: Web/JavaScript/Reference/Global_Objects/Number page-type: javascript-class browser-compat: javascript.builtins.Number --- {{JSRef}} **`Number`** values represent floating-point numbers like `37` or `-9.25`. The `Number` constructor contains constants and methods for working with numbers. Values of other types can be converted to numbers using the `Number()` function. ## Description Numbers are most commonly expressed in literal forms like `255` or `3.14159`. The [lexical grammar](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#numeric_literals) contains a more detailed reference. ```js 255; // two-hundred and fifty-five 255.0; // same number 255 === 255.0; // true 255 === 0xff; // true (hexadecimal notation) 255 === 0b11111111; // true (binary notation) 255 === 0.255e3; // true (decimal exponential notation) ``` A number literal like `37` in JavaScript code is a floating-point value, not an integer. There is no separate integer type in common everyday use. (JavaScript also has a {{jsxref("BigInt")}} type, but it's not designed to replace Number for everyday uses. `37` is still a number, not a BigInt.) When used as a function, `Number(value)` converts a string or other value to the Number type. If the value can't be converted, it returns {{jsxref("NaN")}}. ```js Number("123"); // returns the number 123 Number("123") === 123; // true Number("unicorn"); // NaN Number(undefined); // NaN ``` ### Number encoding The JavaScript `Number` type is a [double-precision 64-bit binary format IEEE 754](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) value, like `double` in Java or C#. This means it can represent fractional values, but there are some limits to the stored number's magnitude and precision. Very briefly, an IEEE 754 double-precision number uses 64 bits to represent 3 parts: - 1 bit for the _sign_ (positive or negative) - 11 bits for the _exponent_ (-1022 to 1023) - 52 bits for the _mantissa_ (representing a number between 0 and 1) The mantissa (also called _significand_) is the part of the number representing the actual value (significant digits). The exponent is the power of 2 that the mantissa should be multiplied by. Thinking about it as scientific notation: <math display="block"><semantics><mrow><mtext>Number</mtext><mo>=</mo><mo stretchy="false">(</mo><mrow><mo>−</mo><mn>1</mn></mrow><msup><mo stretchy="false">)</mo><mtext>sign</mtext></msup><mo>⋅</mo><mo stretchy="false">(</mo><mn>1</mn><mo>+</mo><mtext>mantissa</mtext><mo stretchy="false">)</mo><mo>⋅</mo><msup><mn>2</mn><mtext>exponent</mtext></msup></mrow><annotation encoding="TeX">\text{Number} = ({-1})^{\text{sign}} \cdot (1 + \text{mantissa}) \cdot 2^{\text{exponent}}</annotation></semantics></math> The mantissa is stored with 52 bits, interpreted as digits after `1.…` in a binary fractional number. Therefore, the mantissa's precision is 2<sup>-52</sup> (obtainable via {{jsxref("Number.EPSILON")}}), or about 15 to 17 decimal places; arithmetic above that level of precision is subject to [rounding](https://en.wikipedia.org/wiki/Floating-point_arithmetic#Representable_numbers,_conversion_and_rounding). The largest value a number can hold is 2<sup>1023</sup> × (2 - 2<sup>-52</sup>) (with the exponent being 1023 and the mantissa being 0.1111… in base 2), which is obtainable via {{jsxref("Number.MAX_VALUE")}}. Values higher than that are replaced with the special number constant {{jsxref("Infinity")}}. Integers can only be represented without loss of precision in the range -2<sup>53</sup> + 1 to 2<sup>53</sup> - 1, inclusive (obtainable via {{jsxref("Number.MIN_SAFE_INTEGER")}} and {{jsxref("Number.MAX_SAFE_INTEGER")}}), because the mantissa can only hold 53 bits (including the leading 1). More details on this are described in the [ECMAScript standard](https://tc39.es/ecma262/multipage/ecmascript-data-types-and-values.html#sec-ecmascript-language-types-number-type). ### Number coercion Many built-in operations that expect numbers first coerce their arguments to numbers (which is largely why `Number` objects behave similarly to number primitives). [The operation](https://tc39.es/ecma262/multipage/abstract-operations.html#sec-tonumber) can be summarized as follows: - Numbers are returned as-is. - [`undefined`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) turns into [`NaN`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN). - [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) turns into `0`. - `true` turns into `1`; `false` turns into `0`. - Strings are converted by parsing them as if they contain a [number literal](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#numeric_literals). Parsing failure results in `NaN`. There are some minor differences compared to an actual number literal: - Leading and trailing whitespace/line terminators are ignored. - A leading `0` digit does not cause the number to become an octal literal (or get rejected in strict mode). - `+` and `-` are allowed at the start of the string to indicate its sign. (In actual code, they "look like" part of the literal, but are actually separate unary operators.) However, the sign can only appear once, and must not be followed by whitespace. - `Infinity` and `-Infinity` are recognized as literals. In actual code, they are global variables. - Empty or whitespace-only strings are converted to `0`. - [Numeric separators](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#numeric_separators) are not allowed. - [BigInts](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) throw a {{jsxref("TypeError")}} to prevent unintended implicit coercion causing loss of precision. - [Symbols](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) throw a {{jsxref("TypeError")}}. - Objects are first [converted to a primitive](/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion) by calling their [`[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive) (with `"number"` as hint), `valueOf()`, and `toString()` methods, in that order. The resulting primitive is then converted to a number. There are two ways to achieve nearly the same effect in JavaScript. - [Unary plus](/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus): `+x` does exactly the number coercion steps explained above to convert `x`. - The [`Number()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/Number) function: `Number(x)` uses the same algorithm to convert `x`, except that [BigInts](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) don't throw a {{jsxref("TypeError")}}, but return their number value, with possible loss of precision. {{jsxref("Number.parseFloat()")}} and {{jsxref("Number.parseInt()")}} are similar to `Number()` but only convert strings, and have slightly different parsing rules. For example, `parseInt()` doesn't recognize the decimal point, and `parseFloat()` doesn't recognize the `0x` prefix. #### Integer conversion Some operations expect integers, most notably those that work with array/string indices, date/time components, and number radixes. After performing the number coercion steps above, the result is [truncated](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc) to an integer (by discarding the fractional part). If the number is ±Infinity, it's returned as-is. If the number is `NaN` or `-0`, it's returned as `0`. The result is therefore always an integer (which is not `-0`) or ±Infinity. Notably, when converted to integers, both `undefined` and `null` become `0`, because `undefined` is converted to `NaN`, which also becomes `0`. #### Fixed-width number conversion JavaScript has some lower-level functions that deal with the binary encoding of integer numbers, most notably [bitwise operators](/en-US/docs/Web/JavaScript/Reference/Operators#bitwise_shift_operators) and {{jsxref("TypedArray")}} objects. Bitwise operators always convert the operands to 32-bit integers. In these cases, after converting the value to a number, the number is then normalized to the given width by first [truncating](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc) the fractional part and then taking the lowest bits in the integer's two's complement encoding. ```js new Int32Array([1.1, 1.9, -1.1, -1.9]); // Int32Array(4) [ 1, 1, -1, -1 ] new Int8Array([257, -257]); // Int8Array(2) [ 1, -1 ] // 257 = 0001 0000 0001 // = 0000 0001 (mod 2^8) // = 1 // -257 = 1110 1111 1111 // = 1111 1111 (mod 2^8) // = -1 (as signed integer) new Uint8Array([257, -257]); // Uint8Array(2) [ 1, 255 ] // -257 = 1110 1111 1111 // = 1111 1111 (mod 2^8) // = 255 (as unsigned integer) ``` ## Constructor - {{jsxref("Number/Number", "Number()")}} - : Creates a new `Number` value. When `Number` is called as a constructor (with `new`), it creates a {{jsxref("Number")}} object, which is **not** a primitive. For example, `typeof new Number(42) === "object"`, and `new Number(42) !== 42` (although `new Number(42) == 42`). > **Warning:** You should rarely find yourself using `Number` as a constructor. ## Static properties - {{jsxref("Number.EPSILON")}} - : The smallest interval between two representable numbers. - {{jsxref("Number.MAX_SAFE_INTEGER")}} - : The maximum safe integer in JavaScript (2<sup>53</sup> - 1). - {{jsxref("Number.MAX_VALUE")}} - : The largest positive representable number. - {{jsxref("Number.MIN_SAFE_INTEGER")}} - : The minimum safe integer in JavaScript (-(2<sup>53</sup> - 1)). - {{jsxref("Number.MIN_VALUE")}} - : The smallest positive representable number—that is, the positive number closest to zero (without actually being zero). - {{jsxref("Number.NaN")}} - : Special "**N**ot **a** **N**umber" value. - {{jsxref("Number.NEGATIVE_INFINITY")}} - : Special value representing negative infinity. Returned on overflow. - {{jsxref("Number.POSITIVE_INFINITY")}} - : Special value representing infinity. Returned on overflow. ## Static methods - {{jsxref("Number.isFinite()")}} - : Determine whether the passed value is a finite number. - {{jsxref("Number.isInteger()")}} - : Determine whether the passed value is an integer. - {{jsxref("Number.isNaN()")}} - : Determine whether the passed value is `NaN`. - {{jsxref("Number.isSafeInteger()")}} - : Determine whether the passed value is a safe integer (number between -(2<sup>53</sup> - 1) and 2<sup>53</sup> - 1). - {{jsxref("Number.parseFloat()")}} - : This is the same as the global {{jsxref("parseFloat()")}} function. - {{jsxref("Number.parseInt()")}} - : This is the same as the global {{jsxref("parseInt()")}} function. ## Instance properties These properties are defined on `Number.prototype` and shared by all `Number` instances. - {{jsxref("Object/constructor", "Number.prototype.constructor")}} - : The constructor function that created the instance object. For `Number` instances, the initial value is the {{jsxref("Number/Number", "Number")}} constructor. ## Instance methods - {{jsxref("Number.prototype.toExponential()")}} - : Returns a string representing the number in exponential notation. - {{jsxref("Number.prototype.toFixed()")}} - : Returns a string representing the number in fixed-point notation. - {{jsxref("Number.prototype.toLocaleString()")}} - : Returns a string with a language sensitive representation of this number. Overrides the {{jsxref("Object.prototype.toLocaleString()")}} method. - {{jsxref("Number.prototype.toPrecision()")}} - : Returns a string representing the number to a specified precision in fixed-point or exponential notation. - {{jsxref("Number.prototype.toString()")}} - : Returns a string representing the specified object in the specified _radix_ ("base"). Overrides the {{jsxref("Object.prototype.toString()")}} method. - {{jsxref("Number.prototype.valueOf()")}} - : Returns the primitive value of the specified object. Overrides the {{jsxref("Object.prototype.valueOf()")}} method. ## Examples ### Using the Number object to assign values to numeric variables The following example uses the `Number` object's properties to assign values to several numeric variables: ```js const biggestNum = Number.MAX_VALUE; const smallestNum = Number.MIN_VALUE; const infiniteNum = Number.POSITIVE_INFINITY; const negInfiniteNum = Number.NEGATIVE_INFINITY; const notANum = Number.NaN; ``` ### Integer range for Number The following example shows the minimum and maximum integer values that can be represented as `Number` object. ```js const biggestInt = Number.MAX_SAFE_INTEGER; // (2**53 - 1) => 9007199254740991 const smallestInt = Number.MIN_SAFE_INTEGER; // -(2**53 - 1) => -9007199254740991 ``` When parsing data that has been serialized to JSON, integer values falling outside of this range can be expected to become corrupted when JSON parser coerces them to `Number` type. A possible workaround is to use {{jsxref("String")}} instead. Larger numbers can be represented using the {{jsxref("BigInt")}} type. ### Using Number() to convert a Date object The following example converts the {{jsxref("Date")}} object to a numerical value using `Number` as a function: ```js const d = new Date("1995-12-17T03:24:00"); console.log(Number(d)); ``` This logs `819199440000`. ### Convert numeric strings and null to numbers ```js Number("123"); // 123 Number("123") === 123; // true Number("12.3"); // 12.3 Number("12.00"); // 12 Number("123e-1"); // 12.3 Number(""); // 0 Number(null); // 0 Number("0x11"); // 17 Number("0b11"); // 3 Number("0o11"); // 9 Number("foo"); // NaN Number("100a"); // NaN Number("-Infinity"); // -Infinity ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of modern `Number` behavior (with support binary and octal literals) in `core-js`](https://github.com/zloirock/core-js#ecmascript-number) - {{jsxref("NaN")}} - [Arithmetic operators](/en-US/docs/Web/JavaScript/Reference/Operators#arithmetic_operators) - {{jsxref("Math")}} - {{jsxref("BigInt")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number/min_value/index.md
--- title: Number.MIN_VALUE slug: Web/JavaScript/Reference/Global_Objects/Number/MIN_VALUE page-type: javascript-static-data-property browser-compat: javascript.builtins.Number.MIN_VALUE --- {{JSRef}} The **`Number.MIN_VALUE`** static data property represents the smallest positive numeric value representable in JavaScript. {{EmbedInteractiveExample("pages/js/number-min-value.html")}} ## Value 2<sup>-1074</sup>, or `5E-324`. {{js_property_attributes(0, 0, 0)}} ## 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](https://en.wikipedia.org/wiki/Subnormal_number), 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<sup>-1074</sup>, or `5E-324`. Because `MIN_VALUE` is a static property of {{jsxref("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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Number.MAX_VALUE")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number/max_value/index.md
--- title: Number.MAX_VALUE slug: Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE page-type: javascript-static-data-property browser-compat: javascript.builtins.Number.MAX_VALUE --- {{JSRef}} The **`Number.MAX_VALUE`** static data property represents the maximum numeric value representable in JavaScript. {{EmbedInteractiveExample("pages/js/number-maxvalue.html")}} ## Value 2<sup>1024</sup> - 2<sup>971</sup>, or approximately `1.7976931348623157E+308`. {{js_property_attributes(0, 0, 0)}} ## Description Values larger than `MAX_VALUE` are represented as {{jsxref("Infinity")}} and will lose their actual value. Because `MAX_VALUE` is a static property of {{jsxref("Number")}}, you always use it as `Number.MAX_VALUE`, rather than as a property of a number value. ## Examples ### Using MAX_VALUE The following code multiplies two numeric values. If the result is less than or equal to `MAX_VALUE`, the `func1` function is called; otherwise, the `func2` function is called. ```js if (num1 * num2 <= Number.MAX_VALUE) { func1(); } else { func2(); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Number.MIN_VALUE")}} - {{jsxref("Number")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number/isnan/index.md
--- title: Number.isNaN() slug: Web/JavaScript/Reference/Global_Objects/Number/isNaN page-type: javascript-static-method browser-compat: javascript.builtins.Number.isNaN --- {{JSRef}} The **`Number.isNaN()`** static method determines whether the passed value is the number value {{jsxref("NaN")}}, and returns `false` if the input is not of the Number type. It is a more robust version of the original, global {{jsxref("isNaN()")}} function. {{EmbedInteractiveExample("pages/js/number-isnan.html", "taller")}} ## Syntax ```js-nolint Number.isNaN(value) ``` ### Parameters - `value` - : The value to be tested for {{jsxref("NaN")}}. ### Return value The boolean value `true` if the given value is a number with value {{jsxref("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 [`==`](/en-US/docs/Web/JavaScript/Reference/Operators/Equality) or [`===`](/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality) operators, because unlike all other value comparisons in JavaScript, these evaluate to `false` whenever one operand is {{jsxref("NaN")}}, even if the other operand is also {{jsxref("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 {{jsxref("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 {{jsxref("NaN")}} but aren't actually the same value as {{jsxref("NaN")}}. This also means that only values of the Number type that are also {{jsxref("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 {{jsxref("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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Number.isNaN` in `core-js`](https://github.com/zloirock/core-js#ecmascript-number) - {{jsxref("Number")}} - {{jsxref("isNaN()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number/tostring/index.md
--- title: Number.prototype.toString() slug: Web/JavaScript/Reference/Global_Objects/Number/toString page-type: javascript-instance-method browser-compat: javascript.builtins.Number.toString --- {{JSRef}} The **`toString()`** method of {{jsxref("Number")}} values returns a string representing this number value. {{EmbedInteractiveExample("pages/js/number-tostring.html")}} ## Syntax ```js-nolint toString() toString(radix) ``` ### Parameters - `radix` {{optional_inline}} - : An integer in the range `2` through `36` specifying the base to use for representing the number value. Defaults to 10. ### Return value A string representing the specified number value. ### Exceptions - {{jsxref("RangeError")}} - : Thrown if `radix` is less than 2 or greater than 36. ## Description The {{jsxref("Number")}} object overrides the `toString` method of {{jsxref("Object")}}; it does not inherit {{jsxref("Object.prototype.toString()")}}. For `Number` values, the `toString` method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) `a` through `f` are used. If the specified number value is negative, the sign is preserved. This is the case even if the radix is 2; the string returned is the positive binary representation of the number value preceded by a `-` sign, **not** the two's complement of the number value. Both `0` and `-0` have `"0"` as their string representation. {{jsxref("Infinity")}} returns `"Infinity"` and {{jsxref("NaN")}} returns `"NaN"`. If the number is not a whole number, the decimal point `.` is used to separate the decimal places. [Scientific notation](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#exponential) is used if the radix is 10 and the number's magnitude (ignoring sign) is greater than or equal to 10<sup>21</sup> or less than 10<sup>-6</sup>. In this case, the returned string always explicitly specifies the sign of the exponent. ```js console.log((10 ** 21.5).toString()); // "3.1622776601683794e+21" console.log((10 ** 21.5).toString(8)); // "526665530627250154000000" ``` The `toString()` method requires its `this` value to be a `Number` primitive or wrapper object. It throws a {{jsxref("TypeError")}} for other `this` values without attempting to coerce them to number values. Because `Number` doesn't have a [`[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive) method, JavaScript calls the `toString()` method automatically when a `Number` _object_ is used in a context expecting a string, such as in a [template literal](/en-US/docs/Web/JavaScript/Reference/Template_literals). However, Number _primitive_ values do not consult the `toString()` method to be [coerced to strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) — rather, they are directly converted using the same algorithm as the initial `toString()` implementation. ```js Number.prototype.toString = () => "Overridden"; console.log(`${1}`); // "1" console.log(`${new Number(1)}`); // "Overridden" ``` ## Examples ### Using toString() ```js const count = 10; console.log(count.toString()); // "10" console.log((17).toString()); // "17" console.log((17.2).toString()); // "17.2" const x = 6; console.log(x.toString(2)); // "110" console.log((254).toString(16)); // "fe" console.log((-10).toString(2)); // "-1010" console.log((-0xff).toString(2)); // "-11111111" ``` ### Converting radix of number strings If you have a string representing a number in a non-decimal radix, you can use [`parseInt()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt) and `toString()` to convert it to a different radix. ```js const hex = "CAFEBABE"; const bin = parseInt(hex, 16).toString(2); // "11001010111111101011101010111110" ``` Beware of loss of precision: if the original number string is too large (larger than [`Number.MAX_SAFE_INTEGER`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER), for example), you should use a [`BigInt`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/BigInt) instead. However, the `BigInt` constructor only has support for strings representing number literals (i.e. strings starting with `0b`, `0o`, `0x`). In case your original radix is not one of binary, octal, decimal, or hexadecimal, you may need to hand-write your radix converter, or use a library. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Number.prototype.toFixed()")}} - {{jsxref("Number.prototype.toExponential()")}} - {{jsxref("Number.prototype.toPrecision()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number/negative_infinity/index.md
--- title: Number.NEGATIVE_INFINITY slug: Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY page-type: javascript-static-data-property browser-compat: javascript.builtins.Number.NEGATIVE_INFINITY --- {{JSRef}} The **`Number.NEGATIVE_INFINITY`** static data property represents the negative Infinity value. {{EmbedInteractiveExample("pages/js/number-negative-infinity.html")}} ## Value The same as the negative value of the global {{jsxref("Infinity")}} property. {{js_property_attributes(0, 0, 0)}} ## Description The `Number.NEGATIVE_INFINITY` value behaves slightly differently than mathematical infinity: - Any positive value, including {{jsxref("Number/POSITIVE_INFINITY", "POSITIVE_INFINITY")}}, multiplied by `NEGATIVE_INFINITY` is `NEGATIVE_INFINITY`. - Any negative value, including `NEGATIVE_INFINITY`, multiplied by `NEGATIVE_INFINITY` is {{jsxref("Number/POSITIVE_INFINITY", "POSITIVE_INFINITY")}}. - Any positive value divided by `NEGATIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative value divided by `NEGATIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Zero multiplied by `NEGATIVE_INFINITY` is {{jsxref("NaN")}}. - {{jsxref("NaN")}} multiplied by `NEGATIVE_INFINITY` is {{jsxref("NaN")}}. - `NEGATIVE_INFINITY`, divided by any negative value except `NEGATIVE_INFINITY`, is {{jsxref("Number/POSITIVE_INFINITY", "POSITIVE_INFINITY")}}. - `NEGATIVE_INFINITY`, divided by any positive value except {{jsxref("Number/POSITIVE_INFINITY", "POSITIVE_INFINITY")}}, is `NEGATIVE_INFINITY`. - `NEGATIVE_INFINITY`, divided by either `NEGATIVE_INFINITY` or {{jsxref("Number/POSITIVE_INFINITY", "POSITIVE_INFINITY")}}, is {{jsxref("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 {{jsxref("NaN")}} would be more appropriate in such a case. Because `NEGATIVE_INFINITY` is a static property of {{jsxref("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 {{jsxref("Statements/if...else", "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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Number.POSITIVE_INFINITY")}} - {{jsxref("Number.isFinite()")}} - {{jsxref("Infinity")}} - {{jsxref("isFinite()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number/tofixed/index.md
--- title: Number.prototype.toFixed() slug: Web/JavaScript/Reference/Global_Objects/Number/toFixed page-type: javascript-instance-method browser-compat: javascript.builtins.Number.toFixed --- {{JSRef}} The **`toFixed()`** method of {{jsxref("Number")}} values formats this number using [fixed-point notation](https://en.wikipedia.org/wiki/Fixed-point_arithmetic). {{EmbedInteractiveExample("pages/js/number-tofixed.html")}} ## Syntax ```js-nolint toFixed() toFixed(digits) ``` ### Parameters - `digits` {{optional_inline}} - : The number of digits to appear after the decimal point; should be a value between `0` and `100`, inclusive. If this argument is omitted, it is treated as `0`. ### Return value A string representing the given number using fixed-point notation. ### Exceptions - {{jsxref("RangeError")}} - : Thrown if `digits` is not between `0` and `100` (inclusive). - {{jsxref("TypeError")}} - : Thrown if this method is invoked on an object that is not a {{jsxref("Number")}}. ## Description The `toFixed()` method returns a string representation of a number without using [exponential notation](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential) and with exactly `digits` digits after the decimal point. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If the absolute value of the number is greater or equal to 10<sup>21</sup>, this method uses the same algorithm as {{jsxref("Number.prototype.toString()")}} and returns a string in exponential notation. `toFixed()` returns `"Infinity"`, `"NaN"`, or `"-Infinity"` if the value of the number is non-finite. The output of `toFixed()` may be more precise than [`toString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString) for some values, because `toString()` only prints enough significant digits to distinguish the number from adjacent number values. For example: ```js (1000000000000000128).toString(); // '1000000000000000100' (1000000000000000128).toFixed(0); // '1000000000000000128' ``` However, choosing a `digits` precision that's too high can return unexpected results, because decimal fractional numbers cannot be represented precisely in floating point. For example: ```js (0.3).toFixed(50); // '0.29999999999999998889776975374843459576368331909180' ``` ## Examples ### Using toFixed() ```js const numObj = 12345.6789; numObj.toFixed(); // '12346'; rounding, no fractional part numObj.toFixed(1); // '12345.7'; it rounds up numObj.toFixed(6); // '12345.678900'; additional zeros (1.23e20).toFixed(2); // '123000000000000000000.00' (1.23e-10).toFixed(2); // '0.00' (2.34).toFixed(1); // '2.3' (2.35).toFixed(1); // '2.4'; it rounds up (2.55).toFixed(1); // '2.5' // it rounds down as it can't be represented exactly by a float and the // closest representable float is lower (2.449999999999999999).toFixed(1); // '2.5' // it rounds up as it's less than Number.EPSILON away from 2.45. // This literal actually encodes the same number value as 2.45 (6.02 * 10 ** 23).toFixed(50); // 6.019999999999999e+23; large numbers still use exponential notation ``` ### Using toFixed() with negative numbers Because member access has higher [precedence](/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence) than unary minus, you need to group the negative number expression to get a string. ```js-nolint -2.34.toFixed(1); // -2.3, a number (-2.34).toFixed(1); // '-2.3' ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Number.prototype.toExponential()")}} - {{jsxref("Number.prototype.toPrecision()")}} - {{jsxref("Number.prototype.toString()")}} - {{jsxref("Number.EPSILON")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number/isfinite/index.md
--- title: Number.isFinite() slug: Web/JavaScript/Reference/Global_Objects/Number/isFinite page-type: javascript-static-method browser-compat: javascript.builtins.Number.isFinite --- {{JSRef}} 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 {{jsxref("Infinity")}}, negative `Infinity`, nor {{jsxref("NaN")}}. {{EmbedInteractiveExample("pages/js/number-isfinite.html")}} ## Syntax ```js-nolint 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 {{jsxref("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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Number.isFinite` in `core-js`](https://github.com/zloirock/core-js#ecmascript-number) - {{jsxref("Number")}} - {{jsxref("isFinite()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number/isinteger/index.md
--- title: Number.isInteger() slug: Web/JavaScript/Reference/Global_Objects/Number/isInteger page-type: javascript-static-method browser-compat: javascript.builtins.Number.isInteger --- {{JSRef}} The **`Number.isInteger()`** static method determines whether the passed value is an integer. {{EmbedInteractiveExample("pages/js/number-isinteger.html")}} ## Syntax ```js-nolint Number.isInteger(value) ``` ### Parameters - `value` - : The value to be tested for being an integer. ### Return value The boolean value `true` if the given value is an integer. Otherwise `false`. ## Description If the target value is an integer, return `true`, otherwise return `false`. If the value is {{jsxref("NaN")}} or {{jsxref("Infinity")}}, return `false`. The method will also return `true` for floating point numbers that can be represented as integer. It will always return `false` if the value is not a number. Note that some number literals, while looking like non-integers, actually represent integers — due to the precision limit of ECMAScript floating-point number encoding (IEEE-754). For example, `5.0000000000000001` only differs from `5` by `1e-16`, which is too small to be represented. (For reference, [`Number.EPSILON`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON) stores the distance between 1 and the next representable floating-point number greater than 1, and that is about `2.22e-16`.) Therefore, `5.0000000000000001` will be represented with the same encoding as `5`, thus making `Number.isInteger(5.0000000000000001)` return `true`. In a similar sense, numbers around the magnitude of [`Number.MAX_SAFE_INTEGER`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) will suffer from loss of precision and make `Number.isInteger` return `true` even when it's not an integer. (The actual threshold varies based on how many bits are needed to represent the decimal — for example, `Number.isInteger(4500000000000000.1)` is `true`, but `Number.isInteger(4500000000000000.5)` is `false`.) ## Examples ### Using isInteger ```js Number.isInteger(0); // true Number.isInteger(1); // true Number.isInteger(-100000); // true Number.isInteger(99999999999999999999999); // true Number.isInteger(0.1); // false Number.isInteger(Math.PI); // false Number.isInteger(NaN); // false Number.isInteger(Infinity); // false Number.isInteger(-Infinity); // false Number.isInteger("10"); // false Number.isInteger(true); // false Number.isInteger(false); // false Number.isInteger([1]); // false Number.isInteger(5.0); // true Number.isInteger(5.000000000000001); // false Number.isInteger(5.0000000000000001); // true, because of loss of precision Number.isInteger(4500000000000000.1); // true, because of loss of precision ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Number.isInteger` in `core-js`](https://github.com/zloirock/core-js#ecmascript-number) - {{jsxref("Number")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number/positive_infinity/index.md
--- title: Number.POSITIVE_INFINITY slug: Web/JavaScript/Reference/Global_Objects/Number/POSITIVE_INFINITY page-type: javascript-static-data-property browser-compat: javascript.builtins.Number.POSITIVE_INFINITY --- {{JSRef}} The **`Number.POSITIVE_INFINITY`** static data property represents the positive Infinity value. {{EmbedInteractiveExample("pages/js/number-positive-infinity.html")}} ## Value The same as the value of the global {{jsxref("Infinity")}} property. {{js_property_attributes(0, 0, 0)}} ## 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 {{jsxref("Number/NEGATIVE_INFINITY", "NEGATIVE_INFINITY")}}, multiplied by `POSITIVE_INFINITY` is {{jsxref("Number/NEGATIVE_INFINITY", "NEGATIVE_INFINITY")}}. - Any positive number divided by `POSITIVE_INFINITY` is [positive zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754)). - Any negative number divided by `POSITIVE_INFINITY` is [negative zero](https://en.wikipedia.org/wiki/Signed_zero) (as defined in [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754). - Zero multiplied by `POSITIVE_INFINITY` is {{jsxref("NaN")}}. - {{jsxref("NaN")}} multiplied by `POSITIVE_INFINITY` is {{jsxref("NaN")}}. - `POSITIVE_INFINITY`, divided by any negative value except {{jsxref("Number/NEGATIVE_INFINITY", "NEGATIVE_INFINITY")}}, is {{jsxref("Number/NEGATIVE_INFINITY", "NEGATIVE_INFINITY")}}. - `POSITIVE_INFINITY`, divided by any positive value except `POSITIVE_INFINITY`, is `POSITIVE_INFINITY`. - `POSITIVE_INFINITY`, divided by either {{jsxref("Number/NEGATIVE_INFINITY", "NEGATIVE_INFINITY")}} or `POSITIVE_INFINITY`, is {{jsxref("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 {{jsxref("NaN")}} would be more appropriate in such a case. Because `POSITIVE_INFINITY` is a static property of {{jsxref("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 {{jsxref("Statements/if...else", "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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Number.NEGATIVE_INFINITY")}} - {{jsxref("Number.isFinite()")}} - {{jsxref("Infinity")}} - {{jsxref("isFinite()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number/epsilon/index.md
--- title: Number.EPSILON slug: Web/JavaScript/Reference/Global_Objects/Number/EPSILON page-type: javascript-static-data-property browser-compat: javascript.builtins.Number.EPSILON --- {{JSRef}} The **`Number.EPSILON`** static data property represents the difference between 1 and the smallest floating point number greater than 1. {{EmbedInteractiveExample("pages/js/number-epsilon.html")}} ## Value 2<sup>-52</sup>, or approximately `2.2204460492503130808472633361816E-16`. {{js_property_attributes(0, 0, 0)}} ## Description `Number.EPSILON` is the difference between 1 and the next greater number representable in the Number format, because [double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), and the lowest bit has a significance of 2<sup>-52</sup>. 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. {{jsxref("Number.MIN_VALUE")}} is the smallest representable positive number, which is much smaller than `Number.EPSILON`. Because `EPSILON` is a static property of {{jsxref("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 10<sup>3</sup> 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">`](/en-US/docs/Web/HTML/Attributes/step)), 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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Number.EPSILON` in `core-js`](https://github.com/zloirock/core-js#ecmascript-number) - {{jsxref("Number")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number/parseint/index.md
--- title: Number.parseInt() slug: Web/JavaScript/Reference/Global_Objects/Number/parseInt page-type: javascript-static-method browser-compat: javascript.builtins.Number.parseInt --- {{JSRef}} The **`Number.parseInt()`** static method parses a string argument and returns an integer of the specified radix or base. {{EmbedInteractiveExample("pages/js/number-parseint.html", "taller")}} ## Syntax ```js-nolint Number.parseInt(string) Number.parseInt(string, radix) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading whitespace in this argument is ignored. - `radix` {{optional_inline}} - : An integer between `2` and `36` that represents the _radix_ (the base in mathematical numeral systems) of the `string`. If `radix` is undefined or `0`, it is assumed to be `10` except when the number begins with the code unit pairs `0x` or `0X`, in which case a radix of `16` is assumed. ### Return value An integer parsed from the given `string`. If the `radix` is smaller than `2` or bigger than `36`, or the first non-whitespace character cannot be converted to a number, {{jsxref("NaN")}} is returned. ## Examples ### Number.parseInt vs. parseInt This method has the same functionality as the global {{jsxref("parseInt()")}} function: ```js Number.parseInt === parseInt; // true ``` Its purpose is modularization of globals. Please see {{jsxref("parseInt()")}} for more detail and examples. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Number.parseInt` in `core-js`](https://github.com/zloirock/core-js#ecmascript-number) - {{jsxref("Number")}} - {{jsxref("parseInt()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number/number/index.md
--- title: Number() constructor slug: Web/JavaScript/Reference/Global_Objects/Number/Number page-type: javascript-constructor browser-compat: javascript.builtins.Number.Number --- {{JSRef}} The **`Number()`** constructor creates {{jsxref("Number")}} objects. When called as a function, it returns primitive values of type Number. ## Syntax ```js-nolint new Number(value) Number(value) ``` > **Note:** `Number()` can be called with or without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new), but with different effects. See [Return value](#return_value). ### Parameters - `value` - : The numeric value of the object being created. ### Return value When `Number` is called as a constructor (with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new)), it creates a {{jsxref("Number")}} object, which is **not** a primitive. When `Number` is called as a function, it [coerces the parameter to a number primitive](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion). [BigInts](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) are converted to numbers. If the value can't be converted, it returns {{jsxref("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 example-bad +1n; // TypeError: Cannot convert a BigInt value to a number 0 + 1n; // TypeError: Cannot mix BigInt and other types, use explicit conversions ``` ```js example-good Number(1n); // 1 ``` Note that this may result in loss of precision, if the BigInt is too large to be [safely represented](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). ```js BigInt(Number(2n ** 54n + 1n)) === 2n ** 54n + 1n; // false ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of modern `Number` behavior (with support binary and octal literals) in `core-js`](https://github.com/zloirock/core-js#ecmascript-number) - {{jsxref("NaN")}} - {{jsxref("Math")}} - {{jsxref("BigInt")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number/toprecision/index.md
--- title: Number.prototype.toPrecision() slug: Web/JavaScript/Reference/Global_Objects/Number/toPrecision page-type: javascript-instance-method browser-compat: javascript.builtins.Number.toPrecision --- {{JSRef}} The **`toPrecision()`** method of {{jsxref("Number")}} values returns a string representing this number to the specified precision. {{EmbedInteractiveExample("pages/js/number-toprecision.html")}} ## Syntax ```js-nolint toPrecision() toPrecision(precision) ``` ### Parameters - `precision` {{optional_inline}} - : An integer specifying the number of significant digits. ### Return value A string representing a {{jsxref("Number")}} object in fixed-point or exponential notation rounded to `precision` significant digits. See the discussion of rounding in the description of the {{jsxref("Number.prototype.toFixed()")}} method, which also applies to `toPrecision()`. If the `precision` argument is omitted, behaves as {{jsxref("Number.prototype.toString()")}}. If the `precision` argument is a non-integer value, it is rounded to the nearest integer. ### Exceptions - {{jsxref("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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Number.prototype.toFixed()")}} - {{jsxref("Number.prototype.toExponential()")}} - {{jsxref("Number.prototype.toString()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number/toexponential/index.md
--- title: Number.prototype.toExponential() slug: Web/JavaScript/Reference/Global_Objects/Number/toExponential page-type: javascript-instance-method browser-compat: javascript.builtins.Number.toExponential --- {{JSRef}} The **`toExponential()`** method of {{jsxref("Number")}} values returns a string representing this number in exponential notation. {{EmbedInteractiveExample("pages/js/number-toexponential.html")}} ## Syntax ```js-nolint toExponential() toExponential(fractionDigits) ``` ### Parameters - `fractionDigits` {{optional_inline}} - : 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 {{jsxref("Number")}} object in exponential notation with one digit before the decimal point, rounded to `fractionDigits` digits after the decimal point. ### Exceptions - {{jsxref("RangeError")}} - : Thrown if `fractionDigits` is not between `0` and `100` (inclusive). - {{jsxref("TypeError")}} - : Thrown if this method is invoked on an object that is not a {{jsxref("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 {{jsxref("Number/toFixed", "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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Number.prototype.toExponential` with many bug fixes in `core-js`](https://github.com/zloirock/core-js#ecmascript-number) - {{jsxref("Number.prototype.toFixed()")}} - {{jsxref("Number.prototype.toPrecision()")}} - {{jsxref("Number.prototype.toString()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number/max_safe_integer/index.md
--- title: Number.MAX_SAFE_INTEGER slug: Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER page-type: javascript-static-data-property browser-compat: javascript.builtins.Number.MAX_SAFE_INTEGER --- {{JSRef}} The **`Number.MAX_SAFE_INTEGER`** static data property represents the maximum safe integer in JavaScript (2<sup>53</sup> – 1). For larger integers, consider using {{jsxref("BigInt")}}. {{EmbedInteractiveExample("pages/js/number-maxsafeinteger.html")}} ## Value `9007199254740991` (9,007,199,254,740,991, or \~9 quadrillion). {{js_property_attributes(0, 0, 0)}} ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(2<sup>53</sup> – 1) and 2<sup>53</sup> – 1. "Safe" in this context refers to the ability to represent integers exactly and to compare them correctly. For example, `Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2` will evaluate to true, which is mathematically incorrect. See {{jsxref("Number.isSafeInteger()")}} for more information. Because `MAX_SAFE_INTEGER` is a static property of {{jsxref("Number")}}, you always use it as `Number.MAX_SAFE_INTEGER`, rather than as a property of a number value. ## Examples ### Return value of MAX_SAFE_INTEGER ```js Number.MAX_SAFE_INTEGER; // 9007199254740991 ``` ### Relationship between MAX_SAFE_INTEGER and EPSILON {{jsxref("Number.EPSILON")}} is 2<sup>-52</sup>, while `MAX_SAFE_INTEGER` is 2<sup>53</sup> – 1 — both of them are derived from the width of the mantissa, which is 53 bits (with the highest bit always being 1). Multiplying them will give a value very close — but not equal — to 2. ```js Number.MAX_SAFE_INTEGER * Number.EPSILON; // 1.9999999999999998 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Number.MAX_SAFE_INTEGER` in `core-js`](https://github.com/zloirock/core-js#ecmascript-number) - {{jsxref("Number.MIN_SAFE_INTEGER")}} - {{jsxref("Number.isSafeInteger()")}} - {{jsxref("BigInt")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number/parsefloat/index.md
--- title: Number.parseFloat() slug: Web/JavaScript/Reference/Global_Objects/Number/parseFloat page-type: javascript-static-method browser-compat: javascript.builtins.Number.parseFloat --- {{JSRef}} 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 {{jsxref("NaN")}}. {{EmbedInteractiveExample("pages/js/number-parsefloat.html")}} ## Syntax ```js-nolint Number.parseFloat(string) ``` ### Parameters - `string` - : The value to parse, [coerced to a string](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). Leading {{Glossary("whitespace")}} in this argument is ignored. ### Return value A floating point number parsed from the given `string`. Or {{jsxref("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 {{jsxref("parseFloat()")}} function: ```js Number.parseFloat === parseFloat; // true ``` Its purpose is modularization of globals. See {{jsxref("parseFloat()")}} for more detail and examples. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Number.parseFloat` in `core-js`](https://github.com/zloirock/core-js#ecmascript-number) - {{jsxref("Number")}} - {{jsxref("parseFloat()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number/nan/index.md
--- title: Number.NaN slug: Web/JavaScript/Reference/Global_Objects/Number/NaN page-type: javascript-static-data-property browser-compat: javascript.builtins.Number.NaN --- {{JSRef}} The **`Number.NaN`** static data property represents Not-A-Number, which is equivalent to {{jsxref("NaN")}}. For more information about the behaviors of `NaN`, see the [description for the global property](/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN). {{EmbedInteractiveExample("pages/js/number-nan.html", "taller")}} ## Value The number value {{jsxref("NaN")}}. {{js_property_attributes(0, 0, 0)}} ## Description Because `NaN` is a static property of {{jsxref("Number")}}, you always use it as `Number.NaN`, rather than as a property of a number value. ## Examples ### Checking whether values are numeric ```js function sanitize(x) { if (isNaN(x)) { return Number.NaN; } return x; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("NaN")}} - {{jsxref("Number.isNaN()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number/min_safe_integer/index.md
--- title: Number.MIN_SAFE_INTEGER slug: Web/JavaScript/Reference/Global_Objects/Number/MIN_SAFE_INTEGER page-type: javascript-static-data-property browser-compat: javascript.builtins.Number.MIN_SAFE_INTEGER --- {{JSRef}} The **`Number.MIN_SAFE_INTEGER`** static data property represents the minimum safe integer in JavaScript, or -(2<sup>53</sup> - 1). To represent integers smaller than this, consider using {{jsxref("BigInt")}}. {{EmbedInteractiveExample("pages/js/number-min-safe-integer.html")}} ## Value `-9007199254740991` (-9,007,199,254,740,991, or about -9 quadrillion). {{js_property_attributes(0, 0, 0)}} ## Description [Double precision floating point format](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) only has 52 bits to represent the [mantissa](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding), so it can only safely represent integers between -(2<sup>53</sup> – 1) and 2<sup>53</sup> – 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 {{jsxref("Number.isSafeInteger()")}} for more information. Because `MIN_SAFE_INTEGER` is a static property of {{jsxref("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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Number.MIN_SAFE_INTEGER` in `core-js`](https://github.com/zloirock/core-js#ecmascript-number) - {{jsxref("Number.MAX_SAFE_INTEGER")}} - {{jsxref("Number.isSafeInteger()")}} - {{jsxref("BigInt")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number/valueof/index.md
--- title: Number.prototype.valueOf() slug: Web/JavaScript/Reference/Global_Objects/Number/valueOf page-type: javascript-instance-method browser-compat: javascript.builtins.Number.valueOf --- {{JSRef}} The **`valueOf()`** method of {{jsxref("Number")}} values returns the value of this number. {{EmbedInteractiveExample("pages/js/number-valueof.html")}} ## Syntax ```js-nolint valueOf() ``` ### Parameters None. ### Return value A number representing the primitive value of the specified {{jsxref("Number")}} object. ## Description This method is usually called internally by JavaScript and not explicitly in web code. ## Examples ### Using valueOf ```js const numObj = new Number(10); console.log(typeof numObj); // object const num = numObj.valueOf(); console.log(num); // 10 console.log(typeof num); // number ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Object.prototype.valueOf()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number/tolocalestring/index.md
--- title: Number.prototype.toLocaleString() slug: Web/JavaScript/Reference/Global_Objects/Number/toLocaleString page-type: javascript-instance-method browser-compat: javascript.builtins.Number.toLocaleString --- {{JSRef}} The **`toLocaleString()`** method of {{jsxref("Number")}} values returns a string with a language-sensitive representation of this number. In implementations with [`Intl.NumberFormat` API](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) 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 {{jsxref("Intl.NumberFormat")}} object and use its {{jsxref("Intl/NumberFormat/format", "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. {{EmbedInteractiveExample("pages/js/number-tolocalestring.html")}} ## Syntax ```js-nolint 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](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat), these parameters correspond exactly to the [`Intl.NumberFormat()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/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_inline}} - : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#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_inline}} - : An object adjusting the output format. Corresponds to the [`options`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) parameter of the `Intl.NumberFormat()` constructor. In implementations without `Intl.NumberFormat` support, this parameter is ignored. See the [`Intl.NumberFormat()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat) 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 {{jsxref("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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Intl.NumberFormat")}} - {{jsxref("Number.prototype.toString()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number
data/mdn-content/files/en-us/web/javascript/reference/global_objects/number/issafeinteger/index.md
--- title: Number.isSafeInteger() slug: Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger page-type: javascript-static-method browser-compat: javascript.builtins.Number.isSafeInteger --- {{JSRef}} The **`Number.isSafeInteger()`** static method determines whether the provided value is a number that is a _safe integer_. {{EmbedInteractiveExample("pages/js/number-issafeinteger.html")}} ## Syntax ```js-nolint Number.isSafeInteger(testValue) ``` ### Parameters - `testValue` - : The value to be tested for being a safe integer. ### Return value The boolean value `true` if the given value is a number that is a safe integer. Otherwise `false`. ## Description The safe integers consist of all integers from -(2<sup>53</sup> - 1) to 2<sup>53</sup> - 1, inclusive (±9,007,199,254,740,991). A safe integer is an integer that: - can be exactly represented as an IEEE-754 double precision number, and - whose IEEE-754 representation cannot be the result of rounding any other integer to fit the IEEE-754 representation. For example, 2<sup>53</sup> - 1 is a safe integer: it can be exactly represented, and no other integer rounds to it under any IEEE-754 rounding mode. In contrast, 2<sup>53</sup> is _not_ a safe integer: it can be exactly represented in IEEE-754, but the integer 2<sup>53</sup> + 1 can't be directly represented in IEEE-754 but instead rounds to 2<sup>53</sup> under round-to-nearest and round-to-zero rounding. Handling values larger or smaller than \~9 quadrillion with full precision requires using an [arbitrary precision arithmetic library](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic). See [What Every Programmer Needs to Know about Floating Point Arithmetic](https://floating-point-gui.de/) for more information on floating point representations of numbers. For larger integers, consider using the {{jsxref("BigInt")}} type. ## Examples ### Using isSafeInteger() ```js Number.isSafeInteger(3); // true Number.isSafeInteger(2 ** 53); // false Number.isSafeInteger(2 ** 53 - 1); // true Number.isSafeInteger(NaN); // false Number.isSafeInteger(Infinity); // false Number.isSafeInteger("3"); // false Number.isSafeInteger(3.1); // false Number.isSafeInteger(3.0); // true ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Number.isSafeInteger` in `core-js`](https://github.com/zloirock/core-js#ecmascript-number) - {{jsxref("Number")}} - {{jsxref("Number.MIN_SAFE_INTEGER")}} - {{jsxref("Number.MAX_SAFE_INTEGER")}} - {{jsxref("BigInt")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/uint16array/index.md
--- title: Uint16Array slug: Web/JavaScript/Reference/Global_Objects/Uint16Array page-type: javascript-class browser-compat: javascript.builtins.Uint16Array --- {{JSRef}} The **`Uint16Array`** typed array represents an array of 16-bit unsigned integers in the platform byte order. If control over byte order is needed, use {{jsxref("DataView")}} instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). `Uint16Array` is a subclass of the hidden {{jsxref("TypedArray")}} class. ## Constructor - {{jsxref("Uint16Array/Uint16Array", "Uint16Array()")}} - : Creates a new `Uint16Array` object. ## Static properties _Also inherits static properties from its parent {{jsxref("TypedArray")}}_. - {{jsxref("TypedArray/BYTES_PER_ELEMENT", "Uint16Array.BYTES_PER_ELEMENT")}} - : Returns a number value of the element size. `2` in the case of `Uint16Array`. ## Static methods _Inherits static methods from its parent {{jsxref("TypedArray")}}_. ## Instance properties _Also inherits instance properties from its parent {{jsxref("TypedArray")}}_. These properties are defined on `Uint16Array.prototype` and shared by all `Uint16Array` instances. - {{jsxref("TypedArray/BYTES_PER_ELEMENT", "Uint16Array.prototype.BYTES_PER_ELEMENT")}} - : Returns a number value of the element size. `2` in the case of a `Uint16Array`. - {{jsxref("Object/constructor", "Uint16Array.prototype.constructor")}} - : The constructor function that created the instance object. For `Uint16Array` instances, the initial value is the {{jsxref("Uint16Array/Uint16Array", "Uint16Array")}} constructor. ## Instance methods _Inherits instance methods from its parent {{jsxref("TypedArray")}}_. ## Examples ### Different ways to create a Uint16Array ```js // From a length const uint16 = new Uint16Array(2); uint16[0] = 42; console.log(uint16[0]); // 42 console.log(uint16.length); // 2 console.log(uint16.BYTES_PER_ELEMENT); // 2 // From an array const x = new Uint16Array([21, 31]); console.log(x[1]); // 31 // From another TypedArray const y = new Uint16Array(x); console.log(y[0]); // 21 // From an ArrayBuffer const buffer = new ArrayBuffer(16); const z = new Uint16Array(buffer, 2, 4); console.log(z.byteOffset); // 2 // From an iterable const iterable = (function* () { yield* [1, 2, 3]; })(); const uint16FromIterable = new Uint16Array(iterable); console.log(uint16FromIterable); // Uint16Array [1, 2, 3] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Uint16Array` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays) - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("TypedArray")}} - {{jsxref("ArrayBuffer")}} - {{jsxref("DataView")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/uint16array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/uint16array/uint16array/index.md
--- title: Uint16Array() constructor slug: Web/JavaScript/Reference/Global_Objects/Uint16Array/Uint16Array page-type: javascript-constructor browser-compat: javascript.builtins.Uint16Array.Uint16Array --- {{JSRef}} The **`Uint16Array()`** constructor creates {{jsxref("Uint16Array")}} objects. The contents are initialized to `0`. ## Syntax ```js-nolint new Uint16Array() new Uint16Array(length) new Uint16Array(typedArray) new Uint16Array(object) new Uint16Array(buffer) new Uint16Array(buffer, byteOffset) new Uint16Array(buffer, byteOffset, length) ``` > **Note:** `Uint16Array()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}. ### Parameters See [`TypedArray`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ## Examples ### Different ways to create a Uint16Array ```js // From a length const uint16 = new Uint16Array(2); uint16[0] = 42; console.log(uint16[0]); // 42 console.log(uint16.length); // 2 console.log(uint16.BYTES_PER_ELEMENT); // 2 // From an array const x = new Uint16Array([21, 31]); console.log(x[1]); // 31 // From another TypedArray const y = new Uint16Array(x); console.log(y[0]); // 21 // From an ArrayBuffer const buffer = new ArrayBuffer(16); const z = new Uint16Array(buffer, 2, 4); console.log(z.byteOffset); // 2 // From an iterable const iterable = (function* () { yield* [1, 2, 3]; })(); const uint16FromIterable = new Uint16Array(iterable); console.log(uint16FromIterable); // Uint16Array [1, 2, 3] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Uint16Array` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays) - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("TypedArray")}} - {{jsxref("ArrayBuffer")}} - {{jsxref("DataView")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/float32array/index.md
--- title: Float32Array slug: Web/JavaScript/Reference/Global_Objects/Float32Array page-type: javascript-class browser-compat: javascript.builtins.Float32Array --- {{JSRef}} The **`Float32Array`** typed array represents an array of 32-bit floating point numbers in the platform byte order. If control over byte order is needed, use {{jsxref("DataView")}} instead. The contents are initialized to `0`. Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation). `Float32Array` is a subclass of the hidden {{jsxref("TypedArray")}} class. ## Constructor - {{jsxref("Float32Array/Float32Array", "Float32Array()")}} - : Creates a new `Float32Array` object. ## Static properties _Also inherits static properties from its parent {{jsxref("TypedArray")}}_. - {{jsxref("TypedArray/BYTES_PER_ELEMENT", "Float32Array.BYTES_PER_ELEMENT")}} - : Returns a number value of the element size. `4` in the case of `Float32Array`. ## Static methods _Inherits static methods from its parent {{jsxref("TypedArray")}}_. ## Instance properties _Also inherits instance properties from its parent {{jsxref("TypedArray")}}_. These properties are defined on `Float32Array.prototype` and shared by all `Float32Array` instances. - {{jsxref("TypedArray/BYTES_PER_ELEMENT", "Float32Array.prototype.BYTES_PER_ELEMENT")}} - : Returns a number value of the element size. `4` in the case of a `Float32Array`. - {{jsxref("Object/constructor", "Float32Array.prototype.constructor")}} - : The constructor function that created the instance object. For `Float32Array` instances, the initial value is the {{jsxref("Float32Array/Float32Array", "Float32Array")}} constructor. ## Instance methods _Inherits instance methods from its parent {{jsxref("TypedArray")}}_. ## Examples ### Different ways to create a Float32Array ```js // From a length const float32 = new Float32Array(2); float32[0] = 42; console.log(float32[0]); // 42 console.log(float32.length); // 2 console.log(float32.BYTES_PER_ELEMENT); // 4 // From an array const x = new Float32Array([21, 31]); console.log(x[1]); // 31 // From another TypedArray const y = new Float32Array(x); console.log(y[0]); // 21 // From an ArrayBuffer const buffer = new ArrayBuffer(32); const z = new Float32Array(buffer, 4, 4); console.log(z.byteOffset); // 4 // From an iterable const iterable = (function* () { yield* [1, 2, 3]; })(); const float32FromIterable = new Float32Array(iterable); console.log(float32FromIterable); // Float32Array [1, 2, 3] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Float32Array` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays) - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("TypedArray")}} - {{jsxref("ArrayBuffer")}} - {{jsxref("DataView")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/float32array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/float32array/float32array/index.md
--- title: Float32Array() constructor slug: Web/JavaScript/Reference/Global_Objects/Float32Array/Float32Array page-type: javascript-constructor browser-compat: javascript.builtins.Float32Array.Float32Array --- {{JSRef}} The **`Float32Array()`** constructor creates {{jsxref("Float32Array")}} objects. The contents are initialized to `0`. ## Syntax ```js-nolint new Float32Array() new Float32Array(length) new Float32Array(typedArray) new Float32Array(object) new Float32Array(buffer) new Float32Array(buffer, byteOffset) new Float32Array(buffer, byteOffset, length) ``` > **Note:** `Float32Array()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}. ### Parameters See [`TypedArray`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters). ### Exceptions See [`TypedArray`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions). ## Examples ### Different ways to create a Float32Array ```js // From a length const float32 = new Float32Array(2); float32[0] = 42; console.log(float32[0]); // 42 console.log(float32.length); // 2 console.log(float32.BYTES_PER_ELEMENT); // 4 // From an array const x = new Float32Array([21, 31]); console.log(x[1]); // 31 // From another TypedArray const y = new Float32Array(x); console.log(y[0]); // 21 // From an ArrayBuffer const buffer = new ArrayBuffer(32); const z = new Float32Array(buffer, 4, 4); console.log(z.byteOffset); // 4 // From an iterable const iterable = (function* () { yield* [1, 2, 3]; })(); const float32FromIterable = new Float32Array(iterable); console.log(float32FromIterable); // Float32Array [1, 2, 3] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Float32Array` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays) - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("TypedArray")}} - {{jsxref("ArrayBuffer")}} - {{jsxref("DataView")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/referenceerror/index.md
--- title: ReferenceError slug: Web/JavaScript/Reference/Global_Objects/ReferenceError page-type: javascript-class browser-compat: javascript.builtins.ReferenceError --- {{JSRef}} The **`ReferenceError`** object represents an error when a variable that doesn't exist (or hasn't yet been initialized) in the current scope is referenced. `ReferenceError` is a {{Glossary("serializable object")}}, so it can be cloned with {{domxref("structuredClone()")}} or copied between [Workers](/en-US/docs/Web/API/Worker) using {{domxref("Worker/postMessage()", "postMessage()")}}. `ReferenceError` is a subclass of {{jsxref("Error")}}. ## Constructor - {{jsxref("ReferenceError/ReferenceError", "ReferenceError()")}} - : Creates a new `ReferenceError` object. ## Instance properties _Also inherits instance properties from its parent {{jsxref("Error")}}_. These properties are defined on `ReferenceError.prototype` and shared by all `ReferenceError` instances. - {{jsxref("Object/constructor", "ReferenceError.prototype.constructor")}} - : The constructor function that created the instance object. For `ReferenceError` instances, the initial value is the {{jsxref("ReferenceError/ReferenceError", "ReferenceError")}} constructor. - {{jsxref("Error/name", "ReferenceError.prototype.name")}} - : Represents the name for the type of error. For `ReferenceError.prototype.name`, the initial value is `"ReferenceError"`. ## Instance methods _Inherits instance methods from its parent {{jsxref("Error")}}_. ## Examples ### Catching a ReferenceError ```js try { let a = undefinedVariable; } catch (e) { console.log(e instanceof ReferenceError); // true console.log(e.message); // "undefinedVariable is not defined" console.log(e.name); // "ReferenceError" console.log(e.stack); // Stack of the error } ``` ### Creating a ReferenceError ```js try { throw new ReferenceError("Hello"); } catch (e) { console.log(e instanceof ReferenceError); // true console.log(e.message); // "Hello" console.log(e.name); // "ReferenceError" console.log(e.stack); // Stack of the error } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Error")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/referenceerror
data/mdn-content/files/en-us/web/javascript/reference/global_objects/referenceerror/referenceerror/index.md
--- title: ReferenceError() constructor slug: Web/JavaScript/Reference/Global_Objects/ReferenceError/ReferenceError page-type: javascript-constructor browser-compat: javascript.builtins.ReferenceError.ReferenceError --- {{JSRef}} The **`ReferenceError()`** constructor creates {{jsxref("ReferenceError")}} objects. ## Syntax ```js-nolint new ReferenceError() new ReferenceError(message) new ReferenceError(message, options) new ReferenceError(message, fileName) new ReferenceError(message, fileName, lineNumber) ReferenceError() ReferenceError(message) ReferenceError(message, options) ReferenceError(message, fileName) ReferenceError(message, fileName, lineNumber) ``` > **Note:** `ReferenceError()` can be called with or without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Both create a new `ReferenceError` instance. ### Parameters - `message` {{optional_inline}} - : Human-readable description of the error. - `options` {{optional_inline}} - : An object that has the following properties: - `cause` {{optional_inline}} - : A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error. - `fileName` {{optional_inline}} {{non-standard_inline}} - : The name of the file containing the code that caused the exception. - `lineNumber` {{optional_inline}} {{non-standard_inline}} - : The line number of the code that caused the exception ## Examples ### Catching a ReferenceError ```js try { let a = undefinedVariable; } catch (e) { console.log(e instanceof ReferenceError); // true console.log(e.message); // "undefinedVariable is not defined" console.log(e.name); // "ReferenceError" console.log(e.stack); // Stack of the error } ``` ### Creating a ReferenceError ```js try { throw new ReferenceError("Hello"); } catch (e) { console.log(e instanceof ReferenceError); // true console.log(e.message); // "Hello" console.log(e.name); // "ReferenceError" console.log(e.stack); // Stack of the error } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Error")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics/index.md
--- title: Atomics slug: Web/JavaScript/Reference/Global_Objects/Atomics page-type: javascript-namespace browser-compat: javascript.builtins.Atomics --- {{JSRef}} The **`Atomics`** namespace object contains static methods for carrying out atomic operations. They are used with {{jsxref("SharedArrayBuffer")}} and {{jsxref("ArrayBuffer")}} objects. ## Description Unlike most global objects, `Atomics` is not a constructor. You cannot use it with the [`new` operator](/en-US/docs/Web/JavaScript/Reference/Operators/new) or invoke the `Atomics` object as a function. All properties and methods of `Atomics` are static (just like the {{jsxref("Math")}} object). ### Atomic operations When memory is shared, multiple threads can read and write the same data in memory. Atomic operations make sure that predictable values are written and read, that operations are finished before the next operation starts and that operations are not interrupted. ### Wait and notify The `wait()` and `notify()` methods are modeled on Linux futexes ("fast user-space mutex") and provide ways for waiting until a certain condition becomes true and are typically used as blocking constructs. ## Static properties - `Atomics[@@toStringTag]` - : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"Atomics"`. This property is used in {{jsxref("Object.prototype.toString()")}}. ## Static methods - {{jsxref("Atomics.add()")}} - : Adds the provided value to the existing value at the specified index of the array. Returns the old value at that index. - {{jsxref("Atomics.and()")}} - : Computes a bitwise AND on the value at the specified index of the array with the provided value. Returns the old value at that index. - {{jsxref("Atomics.compareExchange()")}} - : Stores a value at the specified index of the array, if it equals a value. Returns the old value. - {{jsxref("Atomics.exchange()")}} - : Stores a value at the specified index of the array. Returns the old value. - {{jsxref("Atomics.isLockFree()")}} - : An optimization primitive that can be used to determine whether to use locks or atomic operations. Returns `true` if an atomic operation on arrays of the given element size will be implemented using a hardware atomic operation (as opposed to a lock). Experts only. - {{jsxref("Atomics.load()")}} - : Returns the value at the specified index of the array. - {{jsxref("Atomics.notify()")}} - : Notifies agents that are waiting on the specified index of the array. Returns the number of agents that were notified. - {{jsxref("Atomics.or()")}} - : Computes a bitwise OR on the value at the specified index of the array with the provided value. Returns the old value at that index. - {{jsxref("Atomics.store()")}} - : Stores a value at the specified index of the array. Returns the value. - {{jsxref("Atomics.sub()")}} - : Subtracts a value at the specified index of the array. Returns the old value at that index. - {{jsxref("Atomics.wait()")}} - : Verifies that the specified index of the array still contains a value and sleeps awaiting or times out. Returns either `"ok"`, `"not-equal"`, or `"timed-out"`. If waiting is not allowed in the calling agent then it throws an exception. (Most browsers will not allow `wait()` on the browser's main thread.) - {{jsxref("Atomics.waitAsync()")}} - : Waits asynchronously (i.e. without blocking, unlike `Atomics.wait`) on a shared memory location and returns a {{jsxref("Promise")}}. - {{jsxref("Atomics.xor()")}} - : Computes a bitwise XOR on the value at the specified index of the array with the provided value. Returns the old value at that index. ## Examples ### Using Atomics ```js const sab = new SharedArrayBuffer(1024); const ta = new Uint8Array(sab); ta[0]; // 0 ta[0] = 5; // 5 Atomics.add(ta, 0, 12); // 5 Atomics.load(ta, 0); // 17 Atomics.and(ta, 0, 1); // 17 Atomics.load(ta, 0); // 1 Atomics.compareExchange(ta, 0, 5, 12); // 1 Atomics.load(ta, 0); // 1 Atomics.exchange(ta, 0, 12); // 1 Atomics.load(ta, 0); // 12 Atomics.isLockFree(1); // true Atomics.isLockFree(2); // true Atomics.isLockFree(3); // false Atomics.isLockFree(4); // true Atomics.or(ta, 0, 1); // 12 Atomics.load(ta, 0); // 13 Atomics.store(ta, 0, 12); // 12 Atomics.sub(ta, 0, 2); // 12 Atomics.load(ta, 0); // 10 Atomics.xor(ta, 0, 1); // 10 Atomics.load(ta, 0); // 11 ``` ### Waiting and notifying Given a shared `Int32Array`: ```js const sab = new SharedArrayBuffer(1024); const int32 = new Int32Array(sab); ``` A reading thread is sleeping and waiting on location 0 which is expected to be 0. As long as that is true, it will not go on. However, once the writing thread has stored a new value, it will be notified by the writing thread and return the new value (123). ```js Atomics.wait(int32, 0, 0); console.log(int32[0]); // 123 ``` A writing thread stores a new value and notifies the waiting thread once it has written: ```js console.log(int32[0]); // 0; Atomics.store(int32, 0, 123); Atomics.notify(int32, 0, 1); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("ArrayBuffer")}} - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - [Web Workers](/en-US/docs/Web/API/Web_Workers_API) - [Shared Memory – a brief tutorial](https://github.com/tc39/proposal-ecmascript-sharedmem/blob/main/TUTORIAL.md) in the TC39 ecmascript-sharedmem proposal - [A Taste of JavaScript's New Parallel Primitives](https://hacks.mozilla.org/2016/05/a-taste-of-javascripts-new-parallel-primitives/) on hacks.mozilla.org (2016)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics
data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics/store/index.md
--- title: Atomics.store() slug: Web/JavaScript/Reference/Global_Objects/Atomics/store page-type: javascript-static-method browser-compat: javascript.builtins.Atomics.store --- {{JSRef}} The **`Atomics.store()`** static method stores a given value at the given position in the array and returns that value. {{EmbedInteractiveExample("pages/js/atomics-store.html")}} ## Syntax ```js-nolint Atomics.store(typedArray, index, value) ``` ### Parameters - `typedArray` - : An integer typed array. One of {{jsxref("Int8Array")}}, {{jsxref("Uint8Array")}}, {{jsxref("Int16Array")}}, {{jsxref("Uint16Array")}}, {{jsxref("Int32Array")}}, {{jsxref("Uint32Array")}}, {{jsxref("BigInt64Array")}}, or {{jsxref("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 - {{jsxref("TypeError")}} - : Thrown if `typedArray` is not one of the allowed integer types. - {{jsxref("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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Atomics")}} - {{jsxref("Atomics.load()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics
data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics/or/index.md
--- title: Atomics.or() slug: Web/JavaScript/Reference/Global_Objects/Atomics/or page-type: javascript-static-method browser-compat: javascript.builtins.Atomics.or --- {{JSRef}} 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. {{EmbedInteractiveExample("pages/js/atomics-or.html")}} ## Syntax ```js-nolint Atomics.or(typedArray, index, value) ``` ### Parameters - `typedArray` - : An integer typed array. One of {{jsxref("Int8Array")}}, {{jsxref("Uint8Array")}}, {{jsxref("Int16Array")}}, {{jsxref("Uint16Array")}}, {{jsxref("Int32Array")}}, {{jsxref("Uint32Array")}}, {{jsxref("BigInt64Array")}}, or {{jsxref("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 - {{jsxref("TypeError")}} - : Thrown if `typedArray` is not one of the allowed integer types. - {{jsxref("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. ```plain 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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Atomics")}} - {{jsxref("Atomics.and()")}} - {{jsxref("Atomics.xor()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics
data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics/and/index.md
--- title: Atomics.and() slug: Web/JavaScript/Reference/Global_Objects/Atomics/and page-type: javascript-static-method browser-compat: javascript.builtins.Atomics.and --- {{JSRef}} 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. {{EmbedInteractiveExample("pages/js/atomics-and.html")}} ## Syntax ```js-nolint Atomics.and(typedArray, index, value) ``` ### Parameters - `typedArray` - : An integer typed array. One of {{jsxref("Int8Array")}}, {{jsxref("Uint8Array")}}, {{jsxref("Int16Array")}}, {{jsxref("Uint16Array")}}, {{jsxref("Int32Array")}}, {{jsxref("Uint32Array")}}, {{jsxref("BigInt64Array")}}, or {{jsxref("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 - {{jsxref("TypeError")}} - : Thrown if `typedArray` is not one of the allowed integer types. - {{jsxref("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. ```plain 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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Atomics")}} - {{jsxref("Atomics.or()")}} - {{jsxref("Atomics.xor()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics
data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics/xor/index.md
--- title: Atomics.xor() slug: Web/JavaScript/Reference/Global_Objects/Atomics/xor page-type: javascript-static-method browser-compat: javascript.builtins.Atomics.xor --- {{JSRef}} 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. {{EmbedInteractiveExample("pages/js/atomics-xor.html")}} ## Syntax ```js-nolint Atomics.xor(typedArray, index, value) ``` ### Parameters - `typedArray` - : An integer typed array. One of {{jsxref("Int8Array")}}, {{jsxref("Uint8Array")}}, {{jsxref("Int16Array")}}, {{jsxref("Uint16Array")}}, {{jsxref("Int32Array")}}, {{jsxref("Uint32Array")}}, {{jsxref("BigInt64Array")}}, or {{jsxref("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 - {{jsxref("TypeError")}} - : Thrown if `typedArray` is not one of the allowed integer types. - {{jsxref("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. ```plain 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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Atomics")}} - {{jsxref("Atomics.and()")}} - {{jsxref("Atomics.or()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics
data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics/wait/index.md
--- title: Atomics.wait() slug: Web/JavaScript/Reference/Global_Objects/Atomics/wait page-type: javascript-static-method browser-compat: javascript.builtins.Atomics.wait --- {{JSRef}} 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 {{jsxref("Int32Array")}} or {{jsxref("BigInt64Array")}} that views a {{jsxref("SharedArrayBuffer")}}, and may not be allowed on the main thread. > For a non-blocking, asynchronous version of this method, see {{jsxref("Atomics.waitAsync()")}}. ## Syntax ```js-nolint Atomics.wait(typedArray, index, value) Atomics.wait(typedArray, index, value, timeout) ``` ### Parameters - `typedArray` - : An {{jsxref("Int32Array")}} or {{jsxref("BigInt64Array")}} that views a {{jsxref("SharedArrayBuffer")}}. - `index` - : The position in the `typedArray` to wait on. - `value` - : The expected value to test. - `timeout` {{optional_inline}} - : Time to wait in milliseconds. {{jsxref("NaN")}} (and values that get converted to `NaN`, such as `undefined`) becomes {{jsxref("Infinity")}}. Negative values become `0`. ### Return value A string which is either `"ok"`, `"not-equal"`, or `"timed-out"`. ### Exceptions - {{jsxref("TypeError")}} - : Thrown in one of the following cases: - If `typedArray` is not an {{jsxref("Int32Array")}} or {{jsxref("BigInt64Array")}} that views a {{jsxref("SharedArrayBuffer")}}. - If the current thread cannot be blocked (for example, because it's the main thread). - {{jsxref("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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Atomics")}} - {{jsxref("Atomics.waitAsync()")}} - {{jsxref("Atomics.notify()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics
data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics/waitasync/index.md
--- title: Atomics.waitAsync() slug: Web/JavaScript/Reference/Global_Objects/Atomics/waitAsync page-type: javascript-static-method browser-compat: javascript.builtins.Atomics.waitAsync --- {{JSRef}} The **`Atomics.waitAsync()`** static method waits asynchronously on a shared memory location and returns a {{jsxref("Promise")}}. Unlike {{jsxref("Atomics.wait()")}}, `waitAsync` is non-blocking and usable on the main thread. > **Note:** This operation only works with an {{jsxref("Int32Array")}} or {{jsxref("BigInt64Array")}} that views a {{jsxref("SharedArrayBuffer")}}. ## Syntax ```js-nolint Atomics.waitAsync(typedArray, index, value) Atomics.waitAsync(typedArray, index, value, timeout) ``` ### Parameters - `typedArray` - : An {{jsxref("Int32Array")}} or {{jsxref("BigInt64Array")}} that views a {{jsxref("SharedArrayBuffer")}}. - `index` - : The position in the `typedArray` to wait on. - `value` - : The expected value to test. - `timeout` {{optional_inline}} - : Time to wait in milliseconds. {{jsxref("NaN")}} (and values that get converted to `NaN`, such as `undefined`) becomes {{jsxref("Infinity")}}. Negative values become `0`. ### Return value An {{jsxref("Object")}} with the following properties: - `async` - : A boolean indicating whether the `value` property is a {{jsxref("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 {{jsxref("Promise")}} which is fulfilled with a string value, either `"ok"` or `"timed-out"`. The promise is never rejected. ### Exceptions - {{jsxref("TypeError")}} - : Thrown if `typedArray` is not an {{jsxref("Int32Array")}} or {{jsxref("BigInt64Array")}} that views a {{jsxref("SharedArrayBuffer")}}. - {{jsxref("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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Atomics")}} - {{jsxref("Atomics.wait()")}} - {{jsxref("Atomics.notify()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics
data/mdn-content/files/en-us/web/javascript/reference/global_objects/atomics/add/index.md
--- title: Atomics.add() slug: Web/JavaScript/Reference/Global_Objects/Atomics/add page-type: javascript-static-method browser-compat: javascript.builtins.Atomics.add --- {{JSRef}} 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. {{EmbedInteractiveExample("pages/js/atomics-add.html")}} ## Syntax ```js-nolint Atomics.add(typedArray, index, value) ``` ### Parameters - `typedArray` - : An integer typed array. One of {{jsxref("Int8Array")}}, {{jsxref("Uint8Array")}}, {{jsxref("Int16Array")}}, {{jsxref("Uint16Array")}}, {{jsxref("Int32Array")}}, {{jsxref("Uint32Array")}}, {{jsxref("BigInt64Array")}}, or {{jsxref("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 - {{jsxref("TypeError")}} - : Thrown if `typedArray` is not one of the allowed integer types. - {{jsxref("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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Atomics")}} - {{jsxref("Atomics.sub()")}}
0