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/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/find/index.md
--- title: Array.prototype.find() slug: Web/JavaScript/Reference/Global_Objects/Array/find page-type: javascript-instance-method browser-compat: javascript.builtins.Array.find --- {{JSRef}} The **`find()`** method of {{jsxref("Array")}} instances returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, {{jsxref("undefined")}} is returned. - If you need the **index** of the found element in the array, use {{jsxref("Array/findIndex", "findIndex()")}}. - If you need to find the **index of a value**, use {{jsxref("Array/indexOf", "indexOf()")}}. (It's similar to {{jsxref("Array/findIndex", "findIndex()")}}, but checks each element for equality with the value instead of using a testing function.) - If you need to find if a value **exists** in an array, use {{jsxref("Array/includes", "includes()")}}. Again, it checks each element for equality with the value instead of using a testing function. - If you need to find if any element satisfies the provided testing function, use {{jsxref("Array/some", "some()")}}. - If you need to find all elements that satisfy the provided testing function, use {{jsxref("Array/filter", "filter()")}}. {{EmbedInteractiveExample("pages/js/array-find.html", "shorter")}} ## Syntax ```js-nolint find(callbackFn) find(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. 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 in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `find()` was called upon. - `thisArg` {{optional_inline}} - : A value to use as `this` when executing `callbackFn`. See [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). ### Return value The first element in the array that satisfies the provided testing function. Otherwise, {{jsxref("undefined")}} is returned. ## Description The `find()` method is an [iterative method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](/en-US/docs/Glossary/Truthy) value. `find()` then returns that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `find()` returns {{jsxref("undefined")}}. Read the [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods) section for more information about how these methods work in general. `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in [sparse arrays](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays) behave the same as `undefined`. The `find()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. ## Examples ### Find an object in an array by one of its properties ```js const inventory = [ { name: "apples", quantity: 2 }, { name: "bananas", quantity: 0 }, { name: "cherries", quantity: 5 }, ]; function isCherries(fruit) { return fruit.name === "cherries"; } console.log(inventory.find(isCherries)); // { name: 'cherries', quantity: 5 } ``` #### Using arrow function and destructuring ```js const inventory = [ { name: "apples", quantity: 2 }, { name: "bananas", quantity: 0 }, { name: "cherries", quantity: 5 }, ]; const result = inventory.find(({ name }) => name === "cherries"); console.log(result); // { name: 'cherries', quantity: 5 } ``` ### Find a prime number in an array The following example finds an element in the array that is a prime number (or returns {{jsxref("undefined")}} if there is no prime number): ```js function isPrime(element, index, array) { let start = 2; while (start <= Math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found console.log([4, 5, 8, 12].find(isPrime)); // 5 ``` ### Using the third argument of callbackFn The `array` argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses `filter()` to extract the positive values and then uses `find()` to find the first element that is less than its neighbors. ```js const numbers = [3, -1, 1, 4, 1, 5, 9, 2, 6]; const firstTrough = numbers .filter((num) => num > 0) .find((num, idx, arr) => { // Without the arr argument, there's no way to easily access the // intermediate array without saving it to a variable. if (idx > 0 && num >= arr[idx - 1]) return false; if (idx < arr.length - 1 && num >= arr[idx + 1]) return false; return true; }); console.log(firstTrough); // 1 ``` ### Using find() on sparse arrays Empty slots in sparse arrays _are_ visited, and are treated the same as `undefined`. ```js // Declare array with no elements at indexes 2, 3, and 4 const array = [0, 1, , , , 5, 6]; // Shows all indexes, not just those with assigned values array.find((value, index) => { console.log("Visited index", index, "with value", value); }); // Visited index 0 with value 0 // Visited index 1 with value 1 // Visited index 2 with value undefined // Visited index 3 with value undefined // Visited index 4 with value undefined // Visited index 5 with value 5 // Visited index 6 with value 6 // Shows all indexes, including deleted array.find((value, index) => { // Delete element 5 on first iteration if (index === 0) { console.log("Deleting array[5] with value", array[5]); delete array[5]; } // Element 5 is still visited even though deleted console.log("Visited index", index, "with value", value); }); // Deleting array[5] with value 5 // Visited index 0 with value 0 // Visited index 1 with value 1 // Visited index 2 with value undefined // Visited index 3 with value undefined // Visited index 4 with value undefined // Visited index 5 with value undefined // Visited index 6 with value 6 ``` ### Calling find() on non-array objects The `find()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`. ```js const arrayLike = { length: 3, "-1": 0.1, // ignored by find() since -1 < 0 0: 2, 1: 7.3, 2: 4, }; console.log(Array.prototype.find.call(arrayLike, (x) => !Number.isInteger(x))); // 7.3 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.prototype.find` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array.prototype.findIndex()")}} - {{jsxref("Array.prototype.findLast()")}} - {{jsxref("Array.prototype.findLastIndex()")}} - {{jsxref("Array.prototype.includes()")}} - {{jsxref("Array.prototype.filter()")}} - {{jsxref("Array.prototype.every()")}} - {{jsxref("Array.prototype.some()")}} - {{jsxref("TypedArray.prototype.find()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/pop/index.md
--- title: Array.prototype.pop() slug: Web/JavaScript/Reference/Global_Objects/Array/pop page-type: javascript-instance-method browser-compat: javascript.builtins.Array.pop --- {{JSRef}} The **`pop()`** method of {{jsxref("Array")}} instances removes the **last** element from an array and returns that element. This method changes the length of the array. {{EmbedInteractiveExample("pages/js/array-pop.html")}} ## Syntax ```js-nolint pop() ``` ### Parameters None. ### Return value The removed element from the array; {{jsxref("undefined")}} if the array is empty. ## Description The `pop()` method removes the last element from an array and returns that value to the caller. If you call `pop()` on an empty array, it returns {{jsxref("undefined")}}. {{jsxref("Array.prototype.shift()")}} has similar behavior to `pop()`, but applied to the first element in an array. The `pop()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the last element removed, you can use [`arr.slice(0, -1)`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) instead. The `pop()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ## Examples ### Removing the last element of an array The following code creates the `myFish` array containing four elements, then removes its last element. ```js const myFish = ["angel", "clown", "mandarin", "sturgeon"]; const popped = myFish.pop(); console.log(myFish); // ['angel', 'clown', 'mandarin' ] console.log(popped); // 'sturgeon' ``` ### Calling pop() on non-array objects The `pop()` method reads the `length` property of `this`. If the [normalized length](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#normalization_of_the_length_property) is 0, `length` is set to `0` again (whereas it may be negative or `undefined` before). Otherwise, the property at `length - 1` is returned and [deleted](/en-US/docs/Web/JavaScript/Reference/Operators/delete). ```js const arrayLike = { length: 3, unrelated: "foo", 2: 4, }; console.log(Array.prototype.pop.call(arrayLike)); // 4 console.log(arrayLike); // { length: 2, unrelated: 'foo' } const plainObj = {}; // There's no length property, so the length is 0 Array.prototype.pop.call(plainObj); console.log(plainObj); // { length: 0 } ``` ### Using an object in an array-like fashion `push` and `pop` are intentionally generic, and we can use that to our advantage β€” as the following example shows. Note that in this example, we don't create an array to store a collection of objects. Instead, we store the collection on the object itself and use `call` on `Array.prototype.push` and `Array.prototype.pop` to trick those methods into thinking we're dealing with an array. ```js const collection = { length: 0, addElements(...elements) { // obj.length will be incremented automatically // every time an element is added. // Returning what push returns; that is // the new value of length property. return [].push.call(this, ...elements); }, removeElement() { // obj.length will be decremented automatically // every time an element is removed. // Returning what pop returns; that is // the removed element. return [].pop.call(this); }, }; collection.addElements(10, 20, 30); console.log(collection.length); // 3 collection.removeElement(); console.log(collection.length); // 2 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array.prototype.push()")}} - {{jsxref("Array.prototype.shift()")}} - {{jsxref("Array.prototype.unshift()")}} - {{jsxref("Array.prototype.concat()")}} - {{jsxref("Array.prototype.splice()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/unshift/index.md
--- title: Array.prototype.unshift() slug: Web/JavaScript/Reference/Global_Objects/Array/unshift page-type: javascript-instance-method browser-compat: javascript.builtins.Array.unshift --- {{JSRef}} The **`unshift()`** method of {{jsxref("Array")}} instances adds the specified elements to the beginning of an array and returns the new length of the array. {{EmbedInteractiveExample("pages/js/array-unshift.html")}} ## Syntax ```js-nolint unshift() unshift(element1) unshift(element1, element2) unshift(element1, element2, /* …, */ elementN) ``` ### Parameters - `element1`, …, `elementN` - : The elements to add to the front of the `arr`. ### Return value The new {{jsxref("Array/length", "length")}} property of the object upon which the method was called. ## Description The `unshift()` method inserts the given values to the beginning of an array-like object. {{jsxref("Array.prototype.push()")}} has similar behavior to `unshift()`, but applied to the end of an array. Please note that, if multiple elements are passed as parameters, they're inserted in chunk at the beginning of the object, in the exact same order they were passed as parameters. Hence, calling `unshift()` with `n` arguments **once**, or calling it `n` times with **1** argument (with a loop, for example), don't yield the same results. See example: ```js let arr = [4, 5, 6]; arr.unshift(1, 2, 3); console.log(arr); // [1, 2, 3, 4, 5, 6] arr = [4, 5, 6]; // resetting the array arr.unshift(1); arr.unshift(2); arr.unshift(3); console.log(arr); // [3, 2, 1, 4, 5, 6] ``` The `unshift()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ## Examples ### Using unshift() ```js const arr = [1, 2]; arr.unshift(0); // result of the call is 3, which is the new array length // arr is [0, 1, 2] arr.unshift(-2, -1); // the new array length is 5 // arr is [-2, -1, 0, 1, 2] arr.unshift([-4, -3]); // the new array length is 6 // arr is [[-4, -3], -2, -1, 0, 1, 2] arr.unshift([-7, -6], [-5]); // the new array length is 8 // arr is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ] ``` ### Calling unshift() on non-array objects The `unshift()` method reads the `length` property of `this`. It shifts all indices in the range `0` to `length - 1` right by the number of arguments (incrementing their values by this number). Then, it sets each index starting at `0` with the arguments passed to `unshift()`. Finally, it sets the `length` to the previous length plus the number of prepended elements. ```js const arrayLike = { length: 3, unrelated: "foo", 2: 4, }; Array.prototype.unshift.call(arrayLike, 1, 2); console.log(arrayLike); // { '0': 1, '1': 2, '4': 4, length: 5, unrelated: 'foo' } const plainObj = {}; // There's no length property, so the length is 0 Array.prototype.unshift.call(plainObj, 1, 2); console.log(plainObj); // { '0': 1, '1': 2, length: 2 } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.prototype.unshift` in `core-js` with fixes of this method](https://github.com/zloirock/core-js#ecmascript-array) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array.prototype.push()")}} - {{jsxref("Array.prototype.pop()")}} - {{jsxref("Array.prototype.shift()")}} - {{jsxref("Array.prototype.concat()")}} - {{jsxref("Array.prototype.splice()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/findindex/index.md
--- title: Array.prototype.findIndex() slug: Web/JavaScript/Reference/Global_Objects/Array/findIndex page-type: javascript-instance-method browser-compat: javascript.builtins.Array.findIndex --- {{JSRef}} The **`findIndex()`** method of {{jsxref("Array")}} instances returns the index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned. See also the {{jsxref("Array/find", "find()")}} method, which returns the first element that satisfies the testing function (rather than its index). {{EmbedInteractiveExample("pages/js/array-findindex.html", "shorter")}} ## Syntax ```js-nolint findIndex(callbackFn) findIndex(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. 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 in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `findIndex()` was called upon. - `thisArg` {{optional_inline}} - : A value to use as `this` when executing `callbackFn`. See [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). ### Return value The index of the first element in the array that passes the test. Otherwise, `-1`. ## Description The `findIndex()` is an [iterative method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a [truthy](/en-US/docs/Glossary/Truthy) value. `findIndex()` then returns the index of that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `findIndex()` returns `-1`. Read the [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods) section for more information about how these methods work in general. `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in [sparse arrays](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays) behave the same as `undefined`. The `findIndex()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. ## Examples ### Find the index of a prime number in an array The following example returns the index of the first element in the array that is a prime number, or `-1` if there is no prime number. ```js function isPrime(element) { if (element % 2 === 0 || element < 2) { return false; } for (let factor = 3; factor <= Math.sqrt(element); factor += 2) { if (element % factor === 0) { return false; } } return true; } console.log([4, 6, 8, 9, 12].findIndex(isPrime)); // -1, not found console.log([4, 6, 7, 9, 12].findIndex(isPrime)); // 2 (array[2] is 7) ``` ### Using the third argument of callbackFn The `array` argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses `filter()` to extract the positive values and then uses `findIndex()` to find the first element that is less than its neighbors. ```js const numbers = [3, -1, 1, 4, 1, 5, 9, 2, 6]; const firstTrough = numbers .filter((num) => num > 0) .findIndex((num, idx, arr) => { // Without the arr argument, there's no way to easily access the // intermediate array without saving it to a variable. if (idx > 0 && num >= arr[idx - 1]) return false; if (idx < arr.length - 1 && num >= arr[idx + 1]) return false; return true; }); console.log(firstTrough); // 1 ``` ### Using findIndex() on sparse arrays You can search for `undefined` in a sparse array and get the index of an empty slot. ```js console.log([1, , 3].findIndex((x) => x === undefined)); // 1 ``` ### Calling findIndex() on non-array objects The `findIndex()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`. ```js const arrayLike = { length: 3, "-1": 0.1, // ignored by findIndex() since -1 < 0 0: 2, 1: 7.3, 2: 4, }; console.log( Array.prototype.findIndex.call(arrayLike, (x) => !Number.isInteger(x)), ); // 1 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.prototype.findIndex` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array.prototype.find()")}} - {{jsxref("Array.prototype.findLast()")}} - {{jsxref("Array.prototype.findLastIndex()")}} - {{jsxref("Array.prototype.indexOf()")}} - {{jsxref("Array.prototype.lastIndexOf()")}} - {{jsxref("TypedArray.prototype.findIndex()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/keys/index.md
--- title: Array.prototype.keys() slug: Web/JavaScript/Reference/Global_Objects/Array/keys page-type: javascript-instance-method browser-compat: javascript.builtins.Array.keys --- {{JSRef}} The **`keys()`** method of {{jsxref("Array")}} instances returns a new _[array iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator)_ object that contains the keys for each index in the array. {{EmbedInteractiveExample("pages/js/array-keys.html")}} ## Syntax ```js-nolint keys() ``` ### Parameters None. ### Return value A new [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator). ## Description When used on [sparse arrays](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the `keys()` method iterates empty slots as if they have the value `undefined`. The `keys()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. ## Examples ### Using keys() on sparse arrays Unlike {{jsxref("Object.keys()")}}, which only includes keys that actually exist in the array, the `keys()` iterator doesn't ignore holes representing missing properties. ```js const arr = ["a", , "c"]; const sparseKeys = Object.keys(arr); const denseKeys = [...arr.keys()]; console.log(sparseKeys); // ['0', '2'] console.log(denseKeys); // [0, 1, 2] ``` ### Calling keys() on non-array objects The `keys()` method reads the `length` property of `this` and then yields all integer indices between 0 and `length - 1`. No index access actually happens. ```js const arrayLike = { length: 3, }; for (const entry of Array.prototype.keys.call(arrayLike)) { console.log(entry); } // 0 // 1 // 2 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.prototype.keys` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array.prototype.entries()")}} - {{jsxref("Array.prototype.values()")}} - [`Array.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@iterator) - {{jsxref("TypedArray.prototype.keys()")}} - [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/every/index.md
--- title: Array.prototype.every() slug: Web/JavaScript/Reference/Global_Objects/Array/every page-type: javascript-instance-method browser-compat: javascript.builtins.Array.every --- {{JSRef}} The **`every()`** method of {{jsxref("Array")}} instances tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. {{EmbedInteractiveExample("pages/js/array-every.html", "shorter")}} ## Syntax ```js-nolint every(callbackFn) every(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. 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 in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `every()` was called upon. - `thisArg` {{optional_inline}} - : A value to use as `this` when executing `callbackFn`. See [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). ### Return value `true` unless `callbackFn` returns a {{Glossary("falsy")}} value for an array element, in which case `false` is immediately returned. ## Description The `every()` method is an [iterative method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [falsy](/en-US/docs/Glossary/Falsy) value. If such an element is found, `every()` immediately returns `false` and stops iterating through the array. Otherwise, if `callbackFn` returns a [truthy](/en-US/docs/Glossary/Truthy) value for all elements, `every()` returns `true`. Read the [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods) section for more information about how these methods work in general. `every` acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns `true`. (It is [vacuously true](https://en.wikipedia.org/wiki/Vacuous_truth) that all elements of the [empty set](https://en.wikipedia.org/wiki/Empty_set#Properties) satisfy any given condition.) `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in [sparse arrays](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays). The `every()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. ## Examples ### Testing size of all array elements The following example tests whether all elements in the array are 10 or bigger. ```js function isBigEnough(element, index, array) { return element >= 10; } [12, 5, 8, 130, 44].every(isBigEnough); // false [12, 54, 18, 130, 44].every(isBigEnough); // true ``` ### Check if one array is a subset of another array The following example tests if all the elements of an array are present in another array. ```js const isSubset = (array1, array2) => array2.every((element) => array1.includes(element)); console.log(isSubset([1, 2, 3, 4, 5, 6, 7], [5, 7, 6])); // true console.log(isSubset([1, 2, 3, 4, 5, 6, 7], [5, 8, 7])); // false ``` ### Using the third argument of callbackFn The `array` argument is useful if you want to access another element in the array. The following example first uses `filter()` to extract the positive values and then uses `every()` to check whether the array is strictly increasing. ```js const numbers = [-2, 4, -8, 16, -32]; const isIncreasing = numbers .filter((num) => num > 0) .every((num, idx, arr) => { // Without the arr argument, there's no way to easily access the // intermediate array without saving it to a variable. if (idx === 0) return true; return num > arr[idx - 1]; }); console.log(isIncreasing); // true ``` ### Using every() on sparse arrays `every()` will not run its predicate on empty slots. ```js console.log([1, , 3].every((x) => x !== undefined)); // true console.log([2, , 2].every((x) => x === 2)); // true ``` ### Calling every() on non-array objects The `every()` method reads the `length` property of `this` and then accesses each property with a nonnegative integer key less than `length` until they all have been accessed or `callbackFn` returns `false`. ```js const arrayLike = { length: 3, 0: "a", 1: "b", 2: "c", 3: 345, // ignored by every() since length is 3 }; console.log( Array.prototype.every.call(arrayLike, (x) => typeof x === "string"), ); // true ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.prototype.every` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array.prototype.forEach()")}} - {{jsxref("Array.prototype.some()")}} - {{jsxref("Array.prototype.find()")}} - {{jsxref("TypedArray.prototype.every()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/flat/index.md
--- title: Array.prototype.flat() slug: Web/JavaScript/Reference/Global_Objects/Array/flat page-type: javascript-instance-method browser-compat: javascript.builtins.Array.flat --- {{JSRef}} The **`flat()`** method of {{jsxref("Array")}} instances creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. {{EmbedInteractiveExample("pages/js/array-flat.html")}} ## Syntax ```js-nolint flat() flat(depth) ``` ### Parameters - `depth` {{optional_inline}} - : The depth level specifying how deep a nested array structure should be flattened. Defaults to 1. ### Return value A new array with the sub-array elements concatenated into it. ## Description The `flat()` method is a [copying method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#copying_methods_and_mutating_methods). It does not alter `this` but instead returns a [shallow copy](/en-US/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original array. The `flat()` method ignores empty slots if the array being flattened is [sparse](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays). For example, if `depth` is 1, both empty slots in the root array and in the first level of nested arrays are ignored, but empty slots in further nested arrays are preserved with the arrays themselves. The `flat()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. However, its elements must be arrays if they are to be flattened. ## Examples ### Flattening nested arrays ```js const arr1 = [1, 2, [3, 4]]; arr1.flat(); // [1, 2, 3, 4] const arr2 = [1, 2, [3, 4, [5, 6]]]; arr2.flat(); // [1, 2, 3, 4, [5, 6]] const arr3 = [1, 2, [3, 4, [5, 6]]]; arr3.flat(2); // [1, 2, 3, 4, 5, 6] const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]; arr4.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` ### Using flat() on sparse arrays The `flat()` method removes empty slots in arrays: ```js const arr5 = [1, 2, , 4, 5]; console.log(arr5.flat()); // [1, 2, 4, 5] const array = [1, , 3, ["a", , "c"]]; console.log(array.flat()); // [ 1, 3, "a", "c" ] const array2 = [1, , 3, ["a", , ["d", , "e"]]]; console.log(array2.flat()); // [ 1, 3, "a", ["d", empty, "e"] ] console.log(array2.flat(2)); // [ 1, 3, "a", "d", "e"] ``` ### Calling flat() on non-array objects The `flat()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`. If the element is not an array, it's directly appended to the result. If the element is an array, it's flattened according to the `depth` parameter. ```js const arrayLike = { length: 3, 0: [1, 2], // Array-like objects aren't flattened 1: { length: 2, 0: 3, 1: 4 }, 2: 5, 3: 3, // ignored by flat() since length is 3 }; console.log(Array.prototype.flat.call(arrayLike)); // [ 1, 2, { '0': 3, '1': 4, length: 2 }, 5 ] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.prototype.flat` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array.prototype.concat()")}} - {{jsxref("Array.prototype.flatMap()")}} - {{jsxref("Array.prototype.map()")}} - {{jsxref("Array.prototype.reduce()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/findlastindex/index.md
--- title: Array.prototype.findLastIndex() slug: Web/JavaScript/Reference/Global_Objects/Array/findLastIndex page-type: javascript-instance-method browser-compat: javascript.builtins.Array.findLastIndex --- {{JSRef}} The **`findLastIndex()`** method of {{jsxref("Array")}} instances iterates the array in reverse order and returns the index of the first element that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned. See also the {{jsxref("Array/findLast", "findLast()")}} method, which returns the value of last element that satisfies the testing function (rather than its index). {{EmbedInteractiveExample("pages/js/array-findlastindex.html", "shorter")}} ## Syntax ```js-nolint findLastIndex(callbackFn) findLastIndex(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. 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 in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `findLastIndex()` was called upon. - `thisArg` {{optional_inline}} - : A value to use as `this` when executing `callbackFn`. See [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). ### Return value The index of the last (highest-index) element in the array that passes the test. Otherwise `-1` if no matching element is found. ## Description The `findLastIndex()` method is an [iterative method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). It calls a provided `callbackFn` function once for each element in an array in descending-index order, until `callbackFn` returns a [truthy](/en-US/docs/Glossary/Truthy) value. `findLastIndex()` then returns the index of that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `findLastIndex()` returns `-1`. Read the [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods) section for more information about how these methods work in general. `callbackFn` is invoked for _every_ index of the array, not just those with assigned values. Empty slots in [sparse arrays](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays) behave the same as `undefined`. The `findLastIndex()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. ## Examples ### Find the index of the last prime number in an array The following example returns the index of the last element in the array that is a prime number, or `-1` if there is no prime number. ```js function isPrime(element) { if (element % 2 === 0 || element < 2) { return false; } for (let factor = 3; factor <= Math.sqrt(element); factor += 2) { if (element % factor === 0) { return false; } } return true; } console.log([4, 6, 8, 12].findLastIndex(isPrime)); // -1, not found console.log([4, 5, 7, 8, 9, 11, 12].findLastIndex(isPrime)); // 5 ``` ### Using the third argument of callbackFn The `array` argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses `filter()` to extract the positive values and then uses `findLastIndex()` to find the last element that is less than its neighbors. ```js const numbers = [3, -1, 1, 4, 1, 5, 9, 2, 6]; const lastTrough = numbers .filter((num) => num > 0) .findLastIndex((num, idx, arr) => { // Without the arr argument, there's no way to easily access the // intermediate array without saving it to a variable. if (idx > 0 && num >= arr[idx - 1]) return false; if (idx < arr.length - 1 && num >= arr[idx + 1]) return false; return true; }); console.log(lastTrough); // 6 ``` ### Using findLastIndex() on sparse arrays You can search for `undefined` in a sparse array and get the index of an empty slot. ```js console.log([1, , 3].findLastIndex((x) => x === undefined)); // 1 ``` ### Calling findLastIndex() on non-array objects The `findLastIndex()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`. ```js const arrayLike = { length: 3, 0: 2, 1: 7.3, 2: 4, 3: 3, // ignored by findLastIndex() since length is 3 }; console.log( Array.prototype.findLastIndex.call(arrayLike, (x) => Number.isInteger(x)), ); // 2 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.prototype.findLastIndex` in `core-js`](https://github.com/zloirock/core-js#array-find-from-last) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array.prototype.find()")}} - {{jsxref("Array.prototype.findIndex()")}} - {{jsxref("Array.prototype.findLast()")}} - {{jsxref("Array.prototype.indexOf()")}} - {{jsxref("Array.prototype.lastIndexOf()")}} - {{jsxref("TypedArray.prototype.findLastIndex()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/lastindexof/index.md
--- title: Array.prototype.lastIndexOf() slug: Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf page-type: javascript-instance-method browser-compat: javascript.builtins.Array.lastIndexOf --- {{JSRef}} The **`lastIndexOf()`** method of {{jsxref("Array")}} instances returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at `fromIndex`. {{EmbedInteractiveExample("pages/js/array-lastindexof.html")}} ## Syntax ```js-nolint lastIndexOf(searchElement) lastIndexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` {{optional_inline}} - : Zero-based index at which to start searching backwards, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). - Negative index counts back from the end of the array β€” if `-array.length <= fromIndex < 0`, `fromIndex + array.length` is used. - If `fromIndex < -array.length`, the array is not searched and `-1` is returned. You can think of it conceptually as starting at a nonexistent position before the beginning of the array and going backwards from there. There are no array elements on the way, so `searchElement` is never found. - If `fromIndex >= array.length` or `fromIndex` is omitted, `array.length - 1` is used, causing the entire array to be searched. You can think of it conceptually as starting at a nonexistent position beyond the end of the array and going backwards from there. It eventually reaches the real end position of the array, at which point it starts searching backwards through the actual array elements. ### Return value The last index of `searchElement` in the array; `-1` if not found. ## Description The `lastIndexOf()` method compares `searchElement` to elements of the array using [strict equality](/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). [`NaN`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN) values are never compared as equal, so `lastIndexOf()` always returns `-1` when `searchElement` is `NaN`. The `lastIndexOf()` method skips empty slots in [sparse arrays](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays). The `lastIndexOf()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. ## Examples ### Using lastIndexOf() The following example uses `lastIndexOf()` to locate values in an array. ```js const numbers = [2, 5, 9, 2]; numbers.lastIndexOf(2); // 3 numbers.lastIndexOf(7); // -1 numbers.lastIndexOf(2, 3); // 3 numbers.lastIndexOf(2, 2); // 0 numbers.lastIndexOf(2, -2); // 0 numbers.lastIndexOf(2, -1); // 3 ``` You cannot use `lastIndexOf()` to search for `NaN`. ```js const array = [NaN]; array.lastIndexOf(NaN); // -1 ``` ### Finding all the occurrences of an element The following example uses `lastIndexOf` to find all the indices of an element in a given array, using {{jsxref("Array/push", "push()")}} to add them to another array as they are found. ```js const indices = []; const array = ["a", "b", "a", "c", "a", "d"]; const element = "a"; let idx = array.lastIndexOf(element); while (idx !== -1) { indices.push(idx); idx = idx > 0 ? array.lastIndexOf(element, idx - 1) : -1; } console.log(indices); // [4, 2, 0] ``` Note that we have to handle the case `idx === 0` separately here because the element will always be found regardless of the `fromIndex` parameter if it is the first element of the array. This is different from the {{jsxref("Array/indexOf", "indexOf()")}} method. ### Using lastIndexOf() on sparse arrays You cannot use `lastIndexOf()` to search for empty slots in sparse arrays. ```js console.log([1, , 3].lastIndexOf(undefined)); // -1 ``` ### Calling lastIndexOf() on non-array objects The `lastIndexOf()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`. ```js const arrayLike = { length: 3, 0: 2, 1: 3, 2: 2, 3: 5, // ignored by lastIndexOf() since length is 3 }; console.log(Array.prototype.lastIndexOf.call(arrayLike, 2)); // 2 console.log(Array.prototype.lastIndexOf.call(arrayLike, 5)); // -1 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.prototype.lastIndexOf` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array.prototype.findIndex()")}} - {{jsxref("Array.prototype.findLastIndex()")}} - {{jsxref("Array.prototype.indexOf()")}} - {{jsxref("TypedArray.prototype.lastIndexOf()")}} - {{jsxref("String.prototype.lastIndexOf()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/concat/index.md
--- title: Array.prototype.concat() slug: Web/JavaScript/Reference/Global_Objects/Array/concat page-type: javascript-instance-method browser-compat: javascript.builtins.Array.concat --- {{JSRef}} The **`concat()`** method of {{jsxref("Array")}} instances is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array. {{EmbedInteractiveExample("pages/js/array-concat.html", "shorter")}} ## Syntax ```js-nolint concat() concat(value1) concat(value1, value2) concat(value1, value2, /* …, */ valueN) ``` ### Parameters - `value1`, …, `valueN` {{optional_inline}} - : Arrays and/or values to concatenate into a new array. If all `valueN` parameters are omitted, `concat` returns a [shallow copy](/en-US/docs/Glossary/Shallow_copy) of the existing array on which it is called. See the description below for more details. ### Return value A new {{jsxref("Array")}} instance. ## Description The `concat` method creates a new array. The array will first be populated by the elements in the object on which it is called. Then, for each argument, its value will be concatenated into the array β€” for normal objects or primitives, the argument itself will become an element of the final array; for arrays or array-like objects with the property [`Symbol.isConcatSpreadable`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/isConcatSpreadable) set to a truthy value, each element of the argument will be independently added to the final array. The `concat` method does not recurse into nested array arguments. The `concat()` method is a [copying method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#copying_methods_and_mutating_methods). It does not alter `this` or any of the arrays provided as arguments but instead returns a [shallow copy](/en-US/docs/Glossary/Shallow_copy) that contains the same elements as the ones from the original arrays. The `concat()` method preserves empty slots if any of the source arrays is [sparse](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays). The `concat()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). The `this` value is treated in the same way as the other arguments (except it will be converted to an object first), which means plain objects will be directly prepended to the resulting array, while array-like objects with truthy `@@isConcatSpreadable` will be spread into the resulting array. ## Examples ### Concatenating two arrays The following code concatenates two arrays: ```js const letters = ["a", "b", "c"]; const numbers = [1, 2, 3]; const alphaNumeric = letters.concat(numbers); console.log(alphaNumeric); // results in ['a', 'b', 'c', 1, 2, 3] ``` ### Concatenating three arrays The following code concatenates three arrays: ```js const num1 = [1, 2, 3]; const num2 = [4, 5, 6]; const num3 = [7, 8, 9]; const numbers = num1.concat(num2, num3); console.log(numbers); // results in [1, 2, 3, 4, 5, 6, 7, 8, 9] ``` ### Concatenating values to an array The following code concatenates three values to an array: ```js const letters = ["a", "b", "c"]; const alphaNumeric = letters.concat(1, [2, 3]); console.log(alphaNumeric); // results in ['a', 'b', 'c', 1, 2, 3] ``` ### Concatenating nested arrays The following code concatenates nested arrays and demonstrates retention of references: ```js const num1 = [[1]]; const num2 = [2, [3]]; const numbers = num1.concat(num2); console.log(numbers); // results in [[1], 2, [3]] // modify the first element of num1 num1[0].push(4); console.log(numbers); // results in [[1, 4], 2, [3]] ``` ### Concatenating array-like objects with Symbol.isConcatSpreadable `concat` does not treat all array-like objects as arrays by default β€” only if `Symbol.isConcatSpreadable` is set to a truthy value (e.g. `true`). ```js const obj1 = { 0: 1, 1: 2, 2: 3, length: 3 }; const obj2 = { 0: 1, 1: 2, 2: 3, length: 3, [Symbol.isConcatSpreadable]: true }; console.log([0].concat(obj1, obj2)); // [ 0, { '0': 1, '1': 2, '2': 3, length: 3 }, 1, 2, 3 ] ``` ### Using concat() on sparse arrays If any of the source arrays is sparse, the resulting array will also be sparse: ```js console.log([1, , 3].concat([4, 5])); // [1, empty, 3, 4, 5] console.log([1, 2].concat([3, , 5])); // [1, 2, 3, empty, 5] ``` ### Calling concat() on non-array objects If the `this` value is not an array, it is converted to an object and then treated in the same way as the arguments for `concat()`. In this case the return value is always a plain new array. ```js console.log(Array.prototype.concat.call({}, 1, 2, 3)); // [{}, 1, 2, 3] console.log(Array.prototype.concat.call(1, 2, 3)); // [ [Number: 1], 2, 3 ] const arrayLike = { [Symbol.isConcatSpreadable]: true, length: 2, 0: 1, 1: 2, 2: 99, // ignored by concat() since length is 2 }; console.log(Array.prototype.concat.call(arrayLike, 3, 4)); // [1, 2, 3, 4] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.prototype.concat` in `core-js` with fixes and implementation of modern behavior like `Symbol.isConcatSpreadable` support](https://github.com/zloirock/core-js#ecmascript-array) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array.prototype.push()")}} - {{jsxref("Array.prototype.unshift()")}} - {{jsxref("Array.prototype.splice()")}} - {{jsxref("String.prototype.concat()")}} - {{jsxref("Symbol.isConcatSpreadable")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/reduce/index.md
--- title: Array.prototype.reduce() slug: Web/JavaScript/Reference/Global_Objects/Array/reduce page-type: javascript-instance-method browser-compat: javascript.builtins.Array.reduce --- {{JSRef}} The **`reduce()`** method of {{jsxref("Array")}} instances executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value. The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0). {{EmbedInteractiveExample("pages/js/array-reduce.html")}} ## Syntax ```js-nolint reduce(callbackFn) reduce(callbackFn, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. 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 `array[0]`. - `currentValue` - : The value of the current element. On the first call, its value is `array[0]` if `initialValue` is specified; otherwise its value is `array[1]`. - `currentIndex` - : The index position of `currentValue` in the array. On the first call, its value is `0` if `initialValue` is specified, otherwise `1`. - `array` - : The array `reduce()` was called upon. - `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 value in the array as `currentValue`. If `initialValue` is _not_ specified, `accumulator` is initialized to the first value in the array, and `callbackFn` starts executing with the second value in the array as `currentValue`. In this case, if the array 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 array. ### Exceptions - {{jsxref("TypeError")}} - : Thrown if the array contains no elements and `initialValue` is not provided. ## Description The `reduce()` method is an [iterative method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). It runs a "reducer" callback function over all elements in the array, in ascending-index order, and accumulates them into a single value. Every time, the return value of `callbackFn` is passed into `callbackFn` again on next invocation as `accumulator`. The final value of `accumulator` (which is the value returned from `callbackFn` on the final iteration of the array) becomes the return value of `reduce()`. Read the [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods) section for more information about how these methods work in general. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in [sparse arrays](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays). Unlike other [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods), `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict. `reduce()` is a central concept in [functional programming](https://en.wikipedia.org/wiki/Functional_programming), where it's not possible to mutate any value, so in order to accumulate all values in an array, one must return a new accumulator value on every iteration. This convention propagates to JavaScript's `reduce()`: you should use [spreading](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) or other copying methods where possible to create new arrays and objects as the accumulator, rather than mutating the existing one. If you decided to mutate the accumulator instead of copying it, remember to still return the modified object in the callback, or the next iteration will receive undefined. However, note that copying the accumulator may in turn lead to increased memory usage and degraded performance β€” see [When to not use reduce()](#when_to_not_use_reduce) for more details. In such cases, to avoid bad performance and unreadable code, it's better to use a simple `for` loop instead. The `reduce()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. ### Edge cases If the array only has one element (regardless of position) and no `initialValue` is provided, or if `initialValue` is provided but the array is empty, the solo value will be returned _without_ calling `callbackFn`. If `initialValue` is provided and the array is not empty, then the reduce method will always invoke the callback function starting at index 0. If `initialValue` is not provided then the reduce method will act differently for arrays with length larger than 1, equal to 1 and 0, as shown in the following example: ```js const getMax = (a, b) => Math.max(a, b); // callback is invoked for each element in the array starting at index 0 [1, 100].reduce(getMax, 50); // 100 [50].reduce(getMax, 10); // 50 // callback is invoked once for element at index 1 [1, 100].reduce(getMax); // 100 // callback is not invoked [50].reduce(getMax); // 50 [].reduce(getMax, 1); // 1 [].reduce(getMax); // TypeError ``` ## Examples ### How reduce() works without an initial value The code below shows what happens if we call `reduce()` with an array and no initial value. ```js const array = [15, 16, 17, 18, 19]; function reducer(accumulator, currentValue, index) { const returns = accumulator + currentValue; console.log( `accumulator: ${accumulator}, currentValue: ${currentValue}, index: ${index}, returns: ${returns}`, ); return returns; } array.reduce(reducer); ``` The callback would be invoked four times, with the arguments and return values in each call being as follows: | | `accumulator` | `currentValue` | `index` | Return value | | ----------- | ------------- | -------------- | ------- | ------------ | | First call | `15` | `16` | `1` | `31` | | Second call | `31` | `17` | `2` | `48` | | Third call | `48` | `18` | `3` | `66` | | Fourth call | `66` | `19` | `4` | `85` | The `array` parameter never changes through the process β€” it's always `[15, 16, 17, 18, 19]`. The value returned by `reduce()` would be that of the last callback invocation (`85`). ### How reduce() works with an initial value Here we reduce the same array using the same algorithm, but with an `initialValue` of `10` passed as the second argument to `reduce()`: ```js [15, 16, 17, 18, 19].reduce( (accumulator, currentValue) => accumulator + currentValue, 10, ); ``` The callback would be invoked five times, with the arguments and return values in each call being as follows: | | `accumulator` | `currentValue` | `index` | Return value | | ----------- | ------------- | -------------- | ------- | ------------ | | First call | `10` | `15` | `0` | `25` | | Second call | `25` | `16` | `1` | `41` | | Third call | `41` | `17` | `2` | `58` | | Fourth call | `58` | `18` | `3` | `76` | | Fifth call | `76` | `19` | `4` | `95` | The value returned by `reduce()` in this case would be `95`. ### Sum of values in an object array To sum up the values contained in an array of objects, you **must** supply an `initialValue`, so that each item passes through your function. ```js const objects = [{ x: 1 }, { x: 2 }, { x: 3 }]; const sum = objects.reduce( (accumulator, currentValue) => accumulator + currentValue.x, 0, ); console.log(sum); // 6 ``` ### Function sequential piping The `pipe` function takes a sequence of functions and returns a new function. When the new function is called with an argument, the sequence of functions are called in order, which each one receiving the return value of the previous function. ```js const pipe = (...functions) => (initialValue) => functions.reduce((acc, fn) => fn(acc), initialValue); // Building blocks to use for composition const double = (x) => 2 * x; const triple = (x) => 3 * x; const quadruple = (x) => 4 * x; // Composed functions for multiplication of specific values const multiply6 = pipe(double, triple); const multiply9 = pipe(triple, triple); const multiply16 = pipe(quadruple, quadruple); const multiply24 = pipe(double, triple, quadruple); // Usage multiply6(6); // 36 multiply9(9); // 81 multiply16(16); // 256 multiply24(10); // 240 ``` ### Running promises in sequence [Promise sequencing](/en-US/docs/Web/JavaScript/Guide/Using_promises#composition) is essentially function piping demonstrated in the previous section, except done asynchronously. ```js // Compare this with pipe: fn(acc) is changed to acc.then(fn), // and initialValue is ensured to be a promise const asyncPipe = (...functions) => (initialValue) => functions.reduce((acc, fn) => acc.then(fn), Promise.resolve(initialValue)); // Building blocks to use for composition const p1 = async (a) => a * 5; const p2 = async (a) => a * 2; // The composed functions can also return non-promises, because the values are // all eventually wrapped in promises const f3 = (a) => a * 3; const p4 = async (a) => a * 4; asyncPipe(p1, p2, f3, p4)(10).then(console.log); // 1200 ``` `asyncPipe` can also be implemented using `async`/`await`, which better demonstrates its similarity with `pipe`: ```js const asyncPipe = (...functions) => (initialValue) => functions.reduce(async (acc, fn) => fn(await acc), initialValue); ``` ### Using reduce() with sparse arrays `reduce()` skips missing elements in sparse arrays, but it does not skip `undefined` values. ```js console.log([1, 2, , 4].reduce((a, b) => a + b)); // 7 console.log([1, 2, undefined, 4].reduce((a, b) => a + b)); // NaN ``` ### Calling reduce() on non-array objects The `reduce()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`. ```js const arrayLike = { length: 3, 0: 2, 1: 3, 2: 4, 3: 99, // ignored by reduce() since length is 3 }; console.log(Array.prototype.reduce.call(arrayLike, (x, y) => x + y)); // 9 ``` ### When to not use reduce() Multipurpose higher-order functions like `reduce()` can be powerful but sometimes difficult to understand, especially for less-experienced JavaScript developers. If code becomes clearer when using other array methods, developers must weigh the readability tradeoff against the other benefits of using `reduce()`. Note that `reduce()` is always equivalent to a `for...of` loop, except that instead of mutating a variable in the upper scope, we now return the new value for each iteration: ```js const val = array.reduce((acc, cur) => update(acc, cur), initialValue); // Is equivalent to: let val = initialValue; for (const cur of array) { val = update(val, cur); } ``` As previously stated, the reason why people may want to use `reduce()` is to mimic functional programming practices of immutable data. Therefore, developers who uphold the immutability of the accumulator often copy the entire accumulator for each iteration, like this: ```js example-bad const names = ["Alice", "Bob", "Tiff", "Bruce", "Alice"]; const countedNames = names.reduce((allNames, name) => { const currCount = Object.hasOwn(allNames, name) ? allNames[name] : 0; return { ...allNames, [name]: currCount + 1, }; }, {}); ``` This code is ill-performing, because each iteration has to copy the entire `allNames` object, which could be big, depending how many unique names there are. This code has worst-case `O(N^2)` performance, where `N` is the length of `names`. A better alternative is to _mutate_ the `allNames` object on each iteration. However, if `allNames` gets mutated anyway, you may want to convert the `reduce()` to a simple `for` loop instead, which is much clearer: ```js example-bad const names = ["Alice", "Bob", "Tiff", "Bruce", "Alice"]; const countedNames = names.reduce((allNames, name) => { const currCount = allNames[name] ?? 0; allNames[name] = currCount + 1; // return allNames, otherwise the next iteration receives undefined return allNames; }, Object.create(null)); ``` ```js example-good const names = ["Alice", "Bob", "Tiff", "Bruce", "Alice"]; const countedNames = Object.create(null); for (const name of names) { const currCount = countedNames[name] ?? 0; countedNames[name] = currCount + 1; } ``` Therefore, if your accumulator is an array or an object and you are copying the array or object on each iteration, you may accidentally introduce quadratic complexity into your code, causing performance to quickly degrade on large data. This has happened in real-world code β€” see for example [Making Tanstack Table 1000x faster with a 1 line change](https://jpcamara.com/2023/03/07/making-tanstack-table.html). Some of the acceptable use cases of `reduce()` are given above (most notably, summing an array, promise sequencing, and function piping). There are other cases where better alternatives than `reduce()` exist. - Flattening an array of arrays. Use {{jsxref("Array/flat", "flat()")}} instead. ```js example-bad const flattened = array.reduce((acc, cur) => acc.concat(cur), []); ``` ```js example-good const flattened = array.flat(); ``` - Grouping objects by a property. Use {{jsxref("Object.groupBy()")}} instead. ```js example-bad const groups = array.reduce((acc, obj) => { const key = obj.name; const curGroup = acc[key] ?? []; return { ...acc, [key]: [...curGroup, obj] }; }, {}); ``` ```js example-good const groups = Object.groupBy(array, (obj) => obj.name); ``` - Concatenating arrays contained in an array of objects. Use {{jsxref("Array/flatMap", "flatMap()")}} instead. ```js example-bad const friends = [ { name: "Anna", books: ["Bible", "Harry Potter"] }, { name: "Bob", books: ["War and peace", "Romeo and Juliet"] }, { name: "Alice", books: ["The Lord of the Rings", "The Shining"] }, ]; const allBooks = friends.reduce((acc, cur) => [...acc, ...cur.books], []); ``` ```js example-good const allBooks = friends.flatMap((person) => person.books); ``` - Removing duplicate items in an array. Use {{jsxref("Set")}} and {{jsxref("Array.from()")}} instead. ```js example-bad const uniqArray = array.reduce( (acc, cur) => (acc.includes(cur) ? acc : [...acc, cur]), [], ); ``` ```js example-good const uniqArray = Array.from(new Set(array)); ``` - Eliminating or adding elements in an array. Use {{jsxref("Array/flatMap", "flatMap()")}} instead. ```js example-bad // Takes an array of numbers and splits perfect squares into its square roots const roots = array.reduce((acc, cur) => { if (cur < 0) return acc; const root = Math.sqrt(cur); if (Number.isInteger(root)) return [...acc, root, root]; return [...acc, cur]; }, []); ``` ```js example-good const roots = array.flatMap((val) => { if (val < 0) return []; const root = Math.sqrt(val); if (Number.isInteger(root)) return [root, root]; return [val]; }); ``` If you are only eliminating elements from an array, you also can use {{jsxref("Array/filter", "filter()")}}. - Searching for elements or testing if elements satisfy a condition. Use {{jsxref("Array/find", "find()")}} and {{jsxref("Array/find", "findIndex()")}}, or {{jsxref("Array/some", "some()")}} and {{jsxref("Array/every", "every()")}} instead. These methods have the additional benefit that they return as soon as the result is certain, without iterating the entire array. ```js example-bad const allEven = array.reduce((acc, cur) => acc && cur % 2 === 0, true); ``` ```js example-good const allEven = array.every((val) => val % 2 === 0); ``` In cases where `reduce()` is the best choice, documentation and semantic variable naming can help mitigate readability drawbacks. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.prototype.reduce` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array.prototype.map()")}} - {{jsxref("Array.prototype.flat()")}} - {{jsxref("Array.prototype.flatMap()")}} - {{jsxref("Array.prototype.reduceRight()")}} - {{jsxref("TypedArray.prototype.reduce()")}} - {{jsxref("Object.groupBy()")}} - {{jsxref("Map.groupBy()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/tosorted/index.md
--- title: Array.prototype.toSorted() slug: Web/JavaScript/Reference/Global_Objects/Array/toSorted page-type: javascript-instance-method browser-compat: javascript.builtins.Array.toSorted --- {{JSRef}} The **`toSorted()`** method of {{jsxref("Array")}} instances is the [copying](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#copying_methods_and_mutating_methods) version of the {{jsxref("Array/sort", "sort()")}} method. It returns a new array with the elements sorted in ascending order. ## Syntax ```js-nolint toSorted() toSorted(compareFn) ``` ### Parameters - `compareFn` {{optional_inline}} - : Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value. - `a` - : The first element for comparison. - `b` - : The second element for comparison. ### Return value A new array with the elements sorted in ascending order. ## Description See {{jsxref("Array/sort", "sort()")}} for more information on the `compareFn` parameter. When used on [sparse arrays](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the `toSorted()` method iterates empty slots as if they have the value `undefined`. The `toSorted()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. ## Examples ### Sorting an array ```js const months = ["Mar", "Jan", "Feb", "Dec"]; const sortedMonths = months.toSorted(); console.log(sortedMonths); // ['Dec', 'Feb', 'Jan', 'Mar'] console.log(months); // ['Mar', 'Jan', 'Feb', 'Dec'] const values = [1, 10, 21, 2]; const sortedValues = values.toSorted((a, b) => a - b); console.log(sortedValues); // [1, 2, 10, 21] console.log(values); // [1, 10, 21, 2] ``` For more usage examples, see {{jsxref("Array/sort", "sort()")}}. ### Using toSorted() on sparse arrays Empty slots are sorted as if they have the value `undefined`. They are always sorted to the end of the array and `compareFn` is not called for them. ```js console.log(["a", "c", , "b"].toSorted()); // ['a', 'b', 'c', undefined] console.log([, undefined, "a", "b"].toSorted()); // ["a", "b", undefined, undefined] ``` ### Calling toSorted() on non-array objects The `toSorted()` method reads the `length` property of `this`. It then collects all existing integer-keyed properties in the range of `0` to `length - 1`, sorts them, and writes them into a new array. ```js const arrayLike = { length: 3, unrelated: "foo", 0: 5, 2: 4, 3: 3, // ignored by toSorted() since length is 3 }; console.log(Array.prototype.toSorted.call(arrayLike)); // [4, 5, undefined] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.prototype.toSorted` in `core-js`](https://github.com/zloirock/core-js#change-array-by-copy) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array.prototype.sort()")}} - {{jsxref("Array.prototype.toReversed()")}} - {{jsxref("Array.prototype.toSpliced()")}} - {{jsxref("Array.prototype.with()")}} - {{jsxref("TypedArray.prototype.toSorted()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/of/index.md
--- title: Array.of() slug: Web/JavaScript/Reference/Global_Objects/Array/of page-type: javascript-static-method browser-compat: javascript.builtins.Array.of --- {{JSRef}} The **`Array.of()`** static method creates a new `Array` instance from a variable number of arguments, regardless of number or type of the arguments. {{EmbedInteractiveExample("pages/js/array-of.html", "shorter")}} ## Syntax ```js-nolint Array.of() Array.of(element1) Array.of(element1, element2) Array.of(element1, element2, /* …, */ elementN) ``` ### Parameters - `element1`, …, `elementN` - : Elements used to create the array. ### Return value A new {{jsxref("Array")}} instance. ## Description The difference between `Array.of()` and the [`Array()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Array) constructor is in the handling of single arguments: `Array.of(7)` creates an array with a single element, `7`, whereas `Array(7)` creates an empty array with a `length` property of `7`. (That implies an array of 7 empty slots, not slots with actual {{jsxref("undefined")}} values.) ```js Array.of(7); // [7] Array(7); // array of 7 empty slots Array.of(1, 2, 3); // [1, 2, 3] Array(1, 2, 3); // [1, 2, 3] ``` The `Array.of()` method is a generic factory method. For example, if a subclass of `Array` inherits the `of()` method, the inherited `of()` method will return new instances of the subclass instead of `Array` instances. In fact, the `this` value can be any constructor function that accepts a single argument representing the length of the new array, and the constructor will be called with the number of arguments passed to `of()`. The final `length` will be set again when all elements are assigned. If the `this` value is not a constructor function, the plain `Array` constructor is used instead. ## Examples ### Using Array.of() ```js Array.of(1); // [1] Array.of(1, 2, 3); // [1, 2, 3] Array.of(undefined); // [undefined] ``` ### Calling of() on non-array constructors The `of()` method can be called on any constructor function that accepts a single argument representing the length of the new array. ```js function NotArray(len) { console.log("NotArray called with length", len); } console.log(Array.of.call(NotArray, 1, 2, 3)); // NotArray called with length 3 // NotArray { '0': 1, '1': 2, '2': 3, length: 3 } console.log(Array.of.call(Object)); // [Number: 0] { length: 0 } ``` When the `this` value is not a constructor, a plain `Array` object is returned. ```js console.log(Array.of.call({}, 1)); // [ 1 ] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.of` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array/Array", "Array()")}} - {{jsxref("Array.from()")}} - {{jsxref("TypedArray.of()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/values/index.md
--- title: Array.prototype.values() slug: Web/JavaScript/Reference/Global_Objects/Array/values page-type: javascript-instance-method browser-compat: javascript.builtins.Array.values --- {{JSRef}} The **`values()`** method of {{jsxref("Array")}} instances returns a new _[array iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator)_ object that iterates the value of each item in the array. {{EmbedInteractiveExample("pages/js/array-values.html")}} ## Syntax ```js-nolint values() ``` ### Parameters None. ### Return value A new [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator). ## Description `Array.prototype.values()` is the default implementation of [`Array.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@iterator). ```js Array.prototype.values === Array.prototype[Symbol.iterator]; // true ``` When used on [sparse arrays](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the `values()` method iterates empty slots as if they have the value `undefined`. The `values()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. ## Examples ### Iteration using for...of loop Because `values()` returns an iterable iterator, you can use a [`for...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for...of) loop to iterate it. ```js const arr = ["a", "b", "c", "d", "e"]; const iterator = arr.values(); for (const letter of iterator) { console.log(letter); } // "a" "b" "c" "d" "e" ``` ### Iteration using next() Because the return value is also an iterator, you can directly call its `next()` method. ```js const arr = ["a", "b", "c", "d", "e"]; const iterator = arr.values(); iterator.next(); // { value: "a", done: false } iterator.next(); // { value: "b", done: false } iterator.next(); // { value: "c", done: false } iterator.next(); // { value: "d", done: false } iterator.next(); // { value: "e", done: false } iterator.next(); // { value: undefined, done: true } console.log(iterator.next().value); // undefined ``` ### Reusing the iterable > **Warning:** The array iterator object should be a one-time use object. Do not reuse it. The iterable returned from `values()` is not reusable. When `next().done = true` or `currentIndex > length`, [the `for...of` loop ends](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#interactions_between_the_language_and_iteration_protocols), and further iterating it has no effect. ```js const arr = ["a", "b", "c", "d", "e"]; const values = arr.values(); for (const letter of values) { console.log(letter); } // "a" "b" "c" "d" "e" for (const letter of values) { console.log(letter); } // undefined ``` If you use a [`break`](/en-US/docs/Web/JavaScript/Reference/Statements/break) statement to end the iteration early, the iterator can resume from the current position when continuing to iterate it. ```js const arr = ["a", "b", "c", "d", "e"]; const values = arr.values(); for (const letter of values) { console.log(letter); if (letter === "b") { break; } } // "a" "b" for (const letter of values) { console.log(letter); } // "c" "d" "e" ``` ### Mutations during iteration There are no values stored in the array iterator object returned from `values()`; instead, it stores the address of the array used in its creation, and reads the currently visited index on each iteration. Therefore, its iteration output depends on the value stored in that index at the time of stepping. If the values in the array changed, the array iterator object's values change too. ```js const arr = ["a", "b", "c", "d", "e"]; const iterator = arr.values(); console.log(iterator); // Array Iterator { } console.log(iterator.next().value); // "a" arr[1] = "n"; console.log(iterator.next().value); // "n" ``` ### Iterating sparse arrays `values()` will visit empty slots as if they are `undefined`. ```js for (const element of [, "a"].values()) { console.log(element); } // undefined // 'a' ``` ### Calling values() on non-array objects The `values()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`. ```js const arrayLike = { length: 3, 0: "a", 1: "b", 2: "c", 3: "d", // ignored by values() since length is 3 }; for (const entry of Array.prototype.values.call(arrayLike)) { console.log(entry); } // a // b // c ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.prototype.values` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array.prototype.entries()")}} - {{jsxref("Array.prototype.keys()")}} - [`Array.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@iterator) - {{jsxref("TypedArray.prototype.values()")}} - [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/array/index.md
--- title: Array() constructor slug: Web/JavaScript/Reference/Global_Objects/Array/Array page-type: javascript-constructor browser-compat: javascript.builtins.Array.Array --- {{JSRef}} The **`Array()`** constructor creates {{jsxref("Array")}} objects. ## Syntax ```js-nolint new Array() new Array(element1) new Array(element1, element2) new Array(element1, element2, /* …, */ elementN) new Array(arrayLength) Array() Array(element1) Array(element1, element2) Array(element1, element2, /* …, */ elementN) Array(arrayLength) ``` > **Note:** `Array()` can be called with or without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Both create a new `Array` instance. ### Parameters - `element1`, …, `elementN` - : A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the `Array` constructor and that argument is a number (see the `arrayLength` parameter below). Note that this special case only applies to JavaScript arrays created with the `Array` constructor, not array literals created with the square bracket syntax. - `arrayLength` - : If the only argument passed to the `Array` constructor is an integer between 0 and 2<sup>32</sup> - 1 (inclusive), this returns a new JavaScript array with its `length` property set to that number (**Note:** this implies an array of `arrayLength` empty slots, not slots with actual `undefined` values β€” see [sparse arrays](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays)). ### Exceptions - {{jsxref("RangeError")}} - : Thrown if there's only one argument (`arrayLength`) that is a number, but its value is not an integer or not between 0 and 2<sup>32</sup> - 1 (inclusive). ## Examples ### Array literal notation Arrays can be created using the [literal](/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#array_literals) notation: ```js const fruits = ["Apple", "Banana"]; console.log(fruits.length); // 2 console.log(fruits[0]); // "Apple" ``` ### Array constructor with a single parameter Arrays can be created using a constructor with a single number parameter. An array is created with its `length` property set to that number, and the array elements are empty slots. ```js const arrayEmpty = new Array(2); console.log(arrayEmpty.length); // 2 console.log(arrayEmpty[0]); // undefined; actually, it is an empty slot console.log(0 in arrayEmpty); // false console.log(1 in arrayEmpty); // false ``` ```js const arrayOfOne = new Array("2"); // Not the number 2 but the string "2" console.log(arrayOfOne.length); // 1 console.log(arrayOfOne[0]); // "2" ``` ### Array constructor with multiple parameters If more than one argument is passed to the constructor, a new {{jsxref("Array")}} with the given elements is created. ```js const fruits = new Array("Apple", "Banana"); console.log(fruits.length); // 2 console.log(fruits[0]); // "Apple" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/with/index.md
--- title: Array.prototype.with() slug: Web/JavaScript/Reference/Global_Objects/Array/with page-type: javascript-instance-method browser-compat: javascript.builtins.Array.with --- {{JSRef}} The **`with()`** method of {{jsxref("Array")}} instances is the [copying](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#copying_methods_and_mutating_methods) version of using the [bracket notation](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#bracket_notation) to change the value of a given index. It returns a new array with the element at the given index replaced with the given value. ## Syntax ```js-nolint arrayInstance.with(index, value) ``` ### Parameters - `index` - : Zero-based index at which to change the array, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). - Negative index counts back from the end of the array β€” if `-array.length <= index < 0`, `index + array.length` is used. - If the index after normalization is out of bounds, a {{jsxref("RangeError")}} is thrown. - `value` - : Any value to be assigned to the given index. ### Return value A new array with the element at `index` replaced with `value`. ### Exceptions - {{jsxref("RangeError")}} - : Thrown if `index >= array.length` or `index < -array.length`. ## Description The `with()` method changes the value of a given index in the array, returning a new array with the element at the given index replaced with the given value. The original array is not modified. This allows you to chain array methods while doing manipulations. By combining `with()` with {{jsxref("Array/at", "at()")}}, you can both write and read (respectively) an array using negative indices. The `with()` method never produces a [sparse array](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays). If the source array is sparse, the empty slots will be replaced with `undefined` in the new array. The `with()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. ## Examples ### Creating a new array with a single element changed ```js const arr = [1, 2, 3, 4, 5]; console.log(arr.with(2, 6)); // [1, 2, 6, 4, 5] console.log(arr); // [1, 2, 3, 4, 5] ``` ### Chaining array methods With the `with()` method, you can update a single element in an array and then apply other array methods. ```js const arr = [1, 2, 3, 4, 5]; console.log(arr.with(2, 6).map((x) => x ** 2)); // [1, 4, 36, 16, 25] ``` ### Using with() on sparse arrays The `with()` method always creates a dense array. ```js const arr = [1, , 3, 4, , 6]; console.log(arr.with(0, 2)); // [2, undefined, 3, 4, undefined, 6] ``` ### Calling with() on non-array objects The `with()` method creates and returns a new array. It reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`. As each property of `this` is accessed, the array element having an index equal to the key of the property is set to the value of the property. Finally, the array value at `index` is set to `value`. ```js const arrayLike = { length: 3, unrelated: "foo", 0: 5, 2: 4, 3: 3, // ignored by with() since length is 3 }; console.log(Array.prototype.with.call(arrayLike, 0, 1)); // [ 1, undefined, 4 ] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.prototype.with` in `core-js`](https://github.com/zloirock/core-js#change-array-by-copy) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array.prototype.toReversed()")}} - {{jsxref("Array.prototype.toSorted()")}} - {{jsxref("Array.prototype.toSpliced()")}} - {{jsxref("Array.prototype.at()")}} - {{jsxref("TypedArray.prototype.with()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/@@iterator/index.md
--- title: Array.prototype[@@iterator]() slug: Web/JavaScript/Reference/Global_Objects/Array/@@iterator page-type: javascript-instance-method browser-compat: javascript.builtins.Array.@@iterator --- {{JSRef}} The **`[@@iterator]()`** method of {{jsxref("Array")}} instances implements the [iterable protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) and allows arrays to be consumed by most syntaxes expecting iterables, such as the [spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and {{jsxref("Statements/for...of", "for...of")}} loops. It returns an [array iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) that yields the value of each index in the array. The initial value of this property is the same function object as the initial value of the {{jsxref("Array.prototype.values")}} property. {{EmbedInteractiveExample("pages/js/array-prototype-@@iterator.html")}} ## Syntax ```js-nolint array[Symbol.iterator]() ``` ### Parameters None. ### Return value The same return value as {{jsxref("Array.prototype.values()")}}: a new [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) that yields the value of each index in the array. ## Examples ### Iteration using for...of loop Note that you seldom need to call this method directly. The existence of the `@@iterator` method makes arrays [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. #### HTML ```html <ul id="letterResult"></ul> ``` #### JavaScript ```js const arr = ["a", "b", "c"]; const letterResult = document.getElementById("letterResult"); for (const letter of arr) { const li = document.createElement("li"); li.textContent = letter; letterResult.appendChild(li); } ``` #### Result {{EmbedLiveSample("Iteration_using_for...of_loop", "", "")}} ### Manually hand-rolling the iterator You may still manually call the `next()` method of the returned iterator object to achieve maximum control over the iteration process. ```js const arr = ["a", "b", "c", "d", "e"]; const arrIter = arr[Symbol.iterator](); console.log(arrIter.next().value); // a console.log(arrIter.next().value); // b console.log(arrIter.next().value); // c console.log(arrIter.next().value); // d console.log(arrIter.next().value); // e ``` ### Handling strings and string arrays with the same function Because both [strings](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/@@iterator) and arrays implement the iterable protocol, a generic function can be designed to handle both inputs in the same fashion. This is better than calling {{jsxref("Array.prototype.values()")}} directly, which requires the input to be an array, or at least an object with such a method. ```js function logIterable(it) { if (typeof it[Symbol.iterator] !== "function") { console.log(it, "is not iterable."); return; } for (const letter of it) { console.log(letter); } } // Array logIterable(["a", "b", "c"]); // a // b // c // String logIterable("abc"); // a // b // c // Number logIterable(123); // 123 is not iterable. ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.prototype[@@iterator]` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array.prototype.keys()")}} - {{jsxref("Array.prototype.entries()")}} - {{jsxref("Array.prototype.values()")}} - [`TypedArray.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/@@iterator) - [`String.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/@@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/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/@@unscopables/index.md
--- title: Array.prototype[@@unscopables] slug: Web/JavaScript/Reference/Global_Objects/Array/@@unscopables page-type: javascript-instance-data-property browser-compat: javascript.builtins.Array.@@unscopables --- {{JSRef}} The **`@@unscopables`** data property of `Array.prototype` is shared by all {{jsxref("Array")}} instances. It contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored for [`with`](/en-US/docs/Web/JavaScript/Reference/Statements/with) statement-binding purposes. ## Value A [`null`-prototype object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects) with property names given below and their values set to `true`. {{js_property_attributes(0, 0, 1)}} ## Description The default `Array` properties that are ignored for `with` statement-binding purposes are: - [`at()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at) - [`copyWithin()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) - [`entries()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries) - [`fill()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) - [`find()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) - [`findIndex()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex) - [`findLast()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findLast) - [`findLastIndex()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findLastIndex) - [`flat()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) - [`flatMap()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap) - [`includes()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) - [`keys()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys) - [`toReversed()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toReversed) - [`toSorted()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSorted) - [`toSpliced()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSpliced) - [`values()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/values) `Array.prototype[@@unscopables]` is an empty object only containing all the above property names with the value `true`. Its [prototype is `null`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#null-prototype_objects), so `Object.prototype` properties like [`toString`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString) won't accidentally be made unscopable, and a `toString()` within the `with` statement will continue to be called on the array. See {{jsxref("Symbol.unscopables")}} for how to set unscopable properties for your own objects. ## Examples Imagine the `keys.push('something')` call below is in code that was written prior to ECMAScript 2015. ```js var keys = []; with (Array.prototype) { keys.push("something"); } ``` When ECMAScript 2015 introduced the {{jsxref("Array.prototype.keys()")}} method, if the `@@unscopables` data property had not also been introduced, that `keys.push('something')` call would break β€” because the JavaScript runtime would have interpreted `keys` as being the {{jsxref("Array.prototype.keys()")}} method, rather than the `keys` array defined in the example code. So the `@@unscopables` data property for `Array.prototype` causes the `Array` properties introduced in ECMAScript 2015 to be ignored for `with` statement-binding purposes β€” allowing code that was written prior to ECMAScript 2015 to continue working as expected, rather than breaking. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.prototype[@@unscopables]` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Statements/with", "with")}} - {{jsxref("Symbol.unscopables")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/shift/index.md
--- title: Array.prototype.shift() slug: Web/JavaScript/Reference/Global_Objects/Array/shift page-type: javascript-instance-method browser-compat: javascript.builtins.Array.shift --- {{JSRef}} The **`shift()`** method of {{jsxref("Array")}} instances removes the **first** element from an array and returns that removed element. This method changes the length of the array. {{EmbedInteractiveExample("pages/js/array-shift.html")}} ## Syntax ```js-nolint shift() ``` ### Parameters None. ### Return value The removed element from the array; {{jsxref("undefined")}} if the array is empty. ## Description The `shift()` method removes the element at the zeroth index and shifts the values at consecutive indexes down, then returns the removed value. If the {{jsxref("Array/length", "length")}} property is 0, {{jsxref("undefined")}} is returned. The {{jsxref("Array/pop", "pop()")}} method has similar behavior to `shift()`, but applied to the last element in an array. The `shift()` method is a [mutating method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#copying_methods_and_mutating_methods). It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the first element removed, you can use [`arr.slice(1)`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) instead. The `shift()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ## Examples ### Removing an element from an array The following code displays the `myFish` array before and after removing its first element. It also displays the removed element: ```js const myFish = ["angel", "clown", "mandarin", "surgeon"]; console.log("myFish before:", myFish); // myFish before: ['angel', 'clown', 'mandarin', 'surgeon'] const shifted = myFish.shift(); console.log("myFish after:", myFish); // myFish after: ['clown', 'mandarin', 'surgeon'] console.log("Removed this element:", shifted); // Removed this element: angel ``` ### Using shift() method in while loop The shift() method is often used in condition inside while loop. In the following example every iteration will remove the next element from an array, until it is empty: ```js const names = ["Andrew", "Tyrone", "Paul", "Maria", "Gayatri"]; while (typeof (i = names.shift()) !== "undefined") { console.log(i); } // Andrew, Tyrone, Paul, Maria, Gayatri ``` ### Calling shift() on non-array objects The `shift()` method reads the `length` property of `this`. If the [normalized length](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#normalization_of_the_length_property) is 0, `length` is set to `0` again (whereas it may be negative or `undefined` before). Otherwise, the property at `0` is returned, and the rest of the properties are shifted left by one. The `length` property is decremented by one. ```js const arrayLike = { length: 3, unrelated: "foo", 2: 4, }; console.log(Array.prototype.shift.call(arrayLike)); // undefined, because it is an empty slot console.log(arrayLike); // { '1': 4, length: 2, unrelated: 'foo' } const plainObj = {}; // There's no length property, so the length is 0 Array.prototype.shift.call(plainObj); console.log(plainObj); // { length: 0 } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array.prototype.push()")}} - {{jsxref("Array.prototype.pop()")}} - {{jsxref("Array.prototype.unshift()")}} - {{jsxref("Array.prototype.concat()")}} - {{jsxref("Array.prototype.splice()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/some/index.md
--- title: Array.prototype.some() slug: Web/JavaScript/Reference/Global_Objects/Array/some page-type: javascript-instance-method browser-compat: javascript.builtins.Array.some --- {{JSRef}} The **`some()`** method of {{jsxref("Array")}} instances tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array. {{EmbedInteractiveExample("pages/js/array-some.html")}} ## Syntax ```js-nolint some(callbackFn) some(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. 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 in the array. - `index` - : The index of the current element being processed in the array. - `array` - : The array `some()` was called upon. - `thisArg` {{optional_inline}} - : A value to use as `this` when executing `callbackFn`. See [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). ### Return value `false` unless `callbackFn` returns a {{Glossary("truthy")}} value for an array element, in which case `true` is immediately returned. ## Description The `some()` method is an [iterative method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). It calls a provided `callbackFn` function once for each element in an array, until the `callbackFn` returns a [truthy](/en-US/docs/Glossary/Truthy) value. If such an element is found, `some()` immediately returns `true` and stops iterating through the array. Otherwise, if `callbackFn` returns a [falsy](/en-US/docs/Glossary/Falsy) value for all elements, `some()` returns `false`. Read the [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods) section for more information about how these methods work in general. `some()` acts like the "there exists" quantifier in mathematics. In particular, for an empty array, it returns `false` for any condition. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in [sparse arrays](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays). `some()` does not mutate the array on which it is called, but the function provided as `callbackFn` can. Note, however, that the length of the array is saved _before_ the first invocation of `callbackFn`. Therefore: - `callbackFn` will not visit any elements added beyond the array's initial length when the call to `some()` began. - Changes to already-visited indexes do not cause `callbackFn` to be invoked on them again. - If an existing, yet-unvisited element of the array is changed by `callbackFn`, its value passed to the `callbackFn` will be the value at the time that element gets visited. [Deleted](/en-US/docs/Web/JavaScript/Reference/Operators/delete) elements are not visited. > **Warning:** Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases). The `some()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. ## Examples ### Testing value of array elements The following example tests whether any element in the array is bigger than 10. ```js function isBiggerThan10(element, index, array) { return element > 10; } [2, 5, 8, 1, 4].some(isBiggerThan10); // false [12, 5, 8, 1, 4].some(isBiggerThan10); // true ``` ### Testing array elements using arrow functions [Arrow functions](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) provide a shorter syntax for the same test. ```js [2, 5, 8, 1, 4].some((x) => x > 10); // false [12, 5, 8, 1, 4].some((x) => x > 10); // true ``` ### Checking whether a value exists in an array To mimic the function of the `includes()` method, this custom function returns `true` if the element exists in the array: ```js const fruits = ["apple", "banana", "mango", "guava"]; function checkAvailability(arr, val) { return arr.some((arrVal) => val === arrVal); } checkAvailability(fruits, "kela"); // false checkAvailability(fruits, "banana"); // true ``` ### Converting any value to Boolean ```js const TRUTHY_VALUES = [true, "true", 1]; function getBoolean(value) { if (typeof value === "string") { value = value.toLowerCase().trim(); } return TRUTHY_VALUES.some((t) => t === value); } getBoolean(false); // false getBoolean("false"); // false getBoolean(1); // true getBoolean("true"); // true ``` ### Using the third argument of callbackFn The `array` argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses `filter()` to extract the positive values and then uses `some()` to check whether the array is strictly increasing. ```js const numbers = [3, -1, 1, 4, 1, 5]; const isIncreasing = !numbers .filter((num) => num > 0) .some((num, idx, arr) => { // Without the arr argument, there's no way to easily access the // intermediate array without saving it to a variable. if (idx === 0) return false; return num <= arr[idx - 1]; }); console.log(isIncreasing); // false ``` ### Using some() on sparse arrays `some()` will not run its predicate on empty slots. ```js console.log([1, , 3].some((x) => x === undefined)); // false console.log([1, , 1].some((x) => x !== 1)); // false console.log([1, undefined, 1].some((x) => x !== 1)); // true ``` ### Calling some() on non-array objects The `some()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length` until they all have been accessed or `callbackFn` returns `true`. ```js const arrayLike = { length: 3, 0: "a", 1: "b", 2: "c", 3: 3, // ignored by some() since length is 3 }; console.log(Array.prototype.some.call(arrayLike, (x) => typeof x === "number")); // false ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.prototype.some` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array.prototype.every()")}} - {{jsxref("Array.prototype.forEach()")}} - {{jsxref("Array.prototype.find()")}} - {{jsxref("Array.prototype.includes()")}} - {{jsxref("TypedArray.prototype.some()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/tospliced/index.md
--- title: Array.prototype.toSpliced() slug: Web/JavaScript/Reference/Global_Objects/Array/toSpliced page-type: javascript-instance-method browser-compat: javascript.builtins.Array.toSpliced --- {{JSRef}} The **`toSpliced()`** method of {{jsxref("Array")}} instances is the [copying](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#copying_methods_and_mutating_methods) version of the {{jsxref("Array/splice", "splice()")}} method. It returns a new array with some elements removed and/or replaced at a given index. ## Syntax ```js-nolint toSpliced(start) toSpliced(start, deleteCount) toSpliced(start, deleteCount, item1) toSpliced(start, deleteCount, item1, item2) toSpliced(start, deleteCount, item1, item2, /* …, */ itemN) ``` ### Parameters - `start` - : Zero-based index at which to start changing the array, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). - Negative index counts back from the end of the array β€” if `-array.length <= start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no element will be deleted, but the method will behave as an adding function, adding as many elements as provided. - `deleteCount` {{optional_inline}} - : An integer indicating the number of elements in the array to remove from `start`. If `deleteCount` is omitted, or if its value is greater than or equal to the number of elements after the position specified by `start`, then all the elements from `start` to the end of the array will be deleted. However, if you wish to pass any `itemN` parameter, you should pass `Infinity` as `deleteCount` to delete all elements after `start`, because an explicit `undefined` gets [converted](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion) to `0`. If `deleteCount` is `0` or negative, no elements are removed. In this case, you should specify at least one new element (see below). - `item1`, …, `itemN` {{optional_inline}} - : The elements to add to the array, beginning from `start`. If you do not specify any elements, `toSpliced()` will only remove elements from the array. ### Return value A new array that consists of all elements before `start`, `item1`, `item2`, …, `itemN`, and all elements after `start + deleteCount`. ## Description The `toSpliced()` method, like `splice()`, does multiple things at once: it removes the given number of elements from the array, starting at a given index, and then inserts the given elements at the same index. However, it returns a new array instead of modifying the original array. The deleted elements therefore are not returned from this method. The `toSpliced()` method never produces a [sparse array](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays). If the source array is sparse, the empty slots will be replaced with `undefined` in the new array. The `toSpliced()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. ## Examples ### Deleting, adding, and replacing elements You can use `toSpliced()` to delete, add, and replace elements in an array and create a new array more efficiently than using `slice()` and `concat()`. ```js const months = ["Jan", "Mar", "Apr", "May"]; // Inserting an element at index 1 const months2 = months.toSpliced(1, 0, "Feb"); console.log(months2); // ["Jan", "Feb", "Mar", "Apr", "May"] // Deleting two elements starting from index 2 const months3 = months2.toSpliced(2, 2); console.log(months3); // ["Jan", "Feb", "May"] // Replacing one element at index 1 with two new elements const months4 = months3.toSpliced(1, 1, "Feb", "Mar"); console.log(months4); // ["Jan", "Feb", "Mar", "May"] // Original array is not modified console.log(months); // ["Jan", "Mar", "Apr", "May"] ``` ### Using toSpliced() on sparse arrays The `toSpliced()` method always creates a dense array. ```js const arr = [1, , 3, 4, , 6]; console.log(arr.toSpliced(1, 2)); // [1, 4, undefined, 6] ``` ### Calling toSpliced() on non-array objects The `toSpliced()` method reads the `length` property of `this`. It then reads the integer-keyed properties needed and writes them into the new array. ```js const arrayLike = { length: 3, unrelated: "foo", 0: 5, 2: 4, }; console.log(Array.prototype.toSpliced.call(arrayLike, 0, 1, 2, 3)); // [2, 3, undefined, 4] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.prototype.toSpliced` in `core-js`](https://github.com/zloirock/core-js#change-array-by-copy) - {{jsxref("Array.prototype.splice()")}} - {{jsxref("Array.prototype.toReversed()")}} - {{jsxref("Array.prototype.toSorted()")}} - {{jsxref("Array.prototype.with()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/foreach/index.md
--- title: Array.prototype.forEach() slug: Web/JavaScript/Reference/Global_Objects/Array/forEach page-type: javascript-instance-method browser-compat: javascript.builtins.Array.forEach --- {{JSRef}} The **`forEach()`** method of {{jsxref("Array")}} instances executes a provided function once for each array element. {{EmbedInteractiveExample("pages/js/array-foreach.html")}} ## Syntax ```js-nolint forEach(callbackFn) forEach(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. Its return value is discarded. 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. - `array` - : The array `forEach()` was called upon. - `thisArg` {{optional_inline}} - : A value to use as `this` when executing `callbackFn`. See [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). ### Return value None ({{jsxref("undefined")}}). ## Description The `forEach()` method is an [iterative method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). It calls a provided `callbackFn` function once for each element in an array in ascending-index order. Unlike {{jsxref("Array/map", "map()")}}, `forEach()` always returns {{jsxref("undefined")}} and is not chainable. The typical use case is to execute side effects at the end of a chain. Read the [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods) section for more information about how these methods work in general. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in [sparse arrays](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays). The `forEach()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. There is no way to stop or break a `forEach()` loop other than by throwing an exception. If you need such behavior, the `forEach()` method is the wrong tool. Early termination may be accomplished with looping statements like [`for`](/en-US/docs/Web/JavaScript/Reference/Statements/for), [`for...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for...of), and [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in). Array methods like {{jsxref("Array/every", "every()")}}, {{jsxref("Array/some", "some()")}}, {{jsxref("Array/find", "find()")}}, and {{jsxref("Array/findIndex", "findIndex()")}} also stops iteration immediately when further iteration is not necessary. `forEach()` expects a synchronous function β€” it does not wait for promises. Make sure you are aware of the implications while using promises (or async functions) as `forEach` callbacks. ```js const ratings = [5, 4, 5]; let sum = 0; const sumFunction = async (a, b) => a + b; ratings.forEach(async (rating) => { sum = await sumFunction(sum, rating); }); console.log(sum); // Naively expected output: 14 // Actual output: 0 ``` To run a series of asynchronous operations sequentially or concurrently, see [promise composition](/en-US/docs/Web/JavaScript/Guide/Using_promises#composition). ## Examples ### Converting a for loop to forEach ```js const items = ["item1", "item2", "item3"]; const copyItems = []; // before for (let i = 0; i < items.length; i++) { copyItems.push(items[i]); } // after items.forEach((item) => { copyItems.push(item); }); ``` ### Printing the contents of an array > **Note:** In order to display the content of an array in the console, > you can use {{domxref("console/table_static", "console.table()")}}, which prints a formatted > version of the array. > > The following example illustrates an alternative approach, using > `forEach()`. The following code logs a line for each element in an array: ```js const logArrayElements = (element, index /*, array */) => { console.log(`a[${index}] = ${element}`); }; // Notice that index 2 is skipped, since there is no item at // that position in the array. [2, 5, , 9].forEach(logArrayElements); // Logs: // a[0] = 2 // a[1] = 5 // a[3] = 9 ``` ### Using thisArg The following (contrived) example updates an object's properties from each entry in the array: ```js class Counter { constructor() { this.sum = 0; this.count = 0; } add(array) { // Only function expressions have their own this bindings. array.forEach(function countEntry(entry) { this.sum += entry; ++this.count; }, this); } } const obj = new Counter(); obj.add([2, 5, 9]); console.log(obj.count); // 3 console.log(obj.sum); // 16 ``` Since the `thisArg` parameter (`this`) is provided to `forEach()`, it is passed to `callback` each time it's invoked. The callback uses it as its `this` value. > **Note:** If passing the callback function used an > [arrow function expression](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), > the `thisArg` parameter could be omitted, > since all arrow functions lexically bind the {{jsxref("Operators/this", "this")}} > value. ### An object copy function The following code creates a copy of a given object. There are different ways to create a copy of an object. The following is just one way and is presented to explain how `Array.prototype.forEach()` works by using `Object.*` utility functions. ```js const copy = (obj) => { const copy = Object.create(Object.getPrototypeOf(obj)); const propNames = Object.getOwnPropertyNames(obj); propNames.forEach((name) => { const desc = Object.getOwnPropertyDescriptor(obj, name); Object.defineProperty(copy, name, desc); }); return copy; }; const obj1 = { a: 1, b: 2 }; const obj2 = copy(obj1); // obj2 looks like obj1 now ``` ### Flatten an array The following example is only here for learning purpose. If you want to flatten an array using built-in methods, you can use {{jsxref("Array.prototype.flat()")}}. ```js const flatten = (arr) => { const result = []; arr.forEach((item) => { if (Array.isArray(item)) { result.push(...flatten(item)); } else { result.push(item); } }); return result; }; // Usage const nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]]; console.log(flatten(nested)); // [1, 2, 3, 4, 5, 6, 7, 8, 9] ``` ### Using the third argument of callbackFn The `array` argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses `filter()` to extract the positive values and then uses `forEach()` to log its neighbors. ```js const numbers = [3, -1, 1, 4, 1, 5]; numbers .filter((num) => num > 0) .forEach((num, idx, arr) => { // Without the arr argument, there's no way to easily access the // intermediate array without saving it to a variable. console.log(arr[idx - 1], num, arr[idx + 1]); }); // undefined 3 1 // 3 1 4 // 1 4 1 // 4 1 5 // 1 5 undefined ``` ### Using forEach() on sparse arrays ```js-nolint const arraySparse = [1, 3, /* empty */, 7]; let numCallbackRuns = 0; arraySparse.forEach((element) => { console.log({ element }); numCallbackRuns++; }); console.log({ numCallbackRuns }); // { element: 1 } // { element: 3 } // { element: 7 } // { numCallbackRuns: 3 } ``` The callback function is not invoked for the missing value at index 2. ### Calling forEach() on non-array objects The `forEach()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`. ```js const arrayLike = { length: 3, 0: 2, 1: 3, 2: 4, 3: 5, // ignored by forEach() since length is 3 }; Array.prototype.forEach.call(arrayLike, (x) => console.log(x)); // 2 // 3 // 4 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.prototype.forEach` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array.prototype.find()")}} - {{jsxref("Array.prototype.map()")}} - {{jsxref("Array.prototype.filter()")}} - {{jsxref("Array.prototype.every()")}} - {{jsxref("Array.prototype.some()")}} - {{jsxref("TypedArray.prototype.forEach()")}} - {{jsxref("Map.prototype.forEach()")}} - {{jsxref("Set.prototype.forEach()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/fill/index.md
--- title: Array.prototype.fill() slug: Web/JavaScript/Reference/Global_Objects/Array/fill page-type: javascript-instance-method browser-compat: javascript.builtins.Array.fill --- {{JSRef}} The **`fill()`** method of {{jsxref("Array")}} instances changes all elements within a range of indices in an array to a static value. It returns the modified array. {{EmbedInteractiveExample("pages/js/array-fill.html")}} ## Syntax ```js-nolint fill(value) fill(value, start) fill(value, start, end) ``` ### Parameters - `value` - : Value to fill the array with. Note all elements in the array will be this exact value: if `value` is an object, each slot in the array will reference that object. - `start` {{optional_inline}} - : Zero-based index at which to start filling, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). - Negative index counts back from the end of the array β€” if `-array.length <= start < 0`, `start + array.length` is used. - If `start < -array.length` or `start` is omitted, `0` is used. - If `start >= array.length`, no index is filled. - `end` {{optional_inline}} - : Zero-based index at which to end filling, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). `fill()` fills up to but not including `end`. - Negative index counts back from the end of the array β€” if `-array.length <= end < 0`, `end + array.length` is used. - If `end < -array.length`, `0` is used. - If `end >= array.length` or `end` is omitted, `array.length` is used, causing all indices until the end to be filled. - If `end` implies a position before or at the position that `start` implies, nothing is filled. ### Return value The modified array, filled with `value`. ## Description The `fill()` method is a [mutating method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#copying_methods_and_mutating_methods). It does not alter the length of `this`, but it will change the content of `this`. The `fill()` method fills empty slots in [sparse](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays) arrays with `value` as well. The `fill()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. > **Note:** Using `Array.prototype.fill()` on an empty array (`length = 0`) would not modify it as the array has nothing to be modified. > To use `Array.prototype.fill()` when declaring an array, make sure the array has non-zero `length`. > [See example](#using_fill_to_populate_an_empty_array). ## Examples ### Using fill() ```js console.log([1, 2, 3].fill(4)); // [4, 4, 4] console.log([1, 2, 3].fill(4, 1)); // [1, 4, 4] console.log([1, 2, 3].fill(4, 1, 2)); // [1, 4, 3] console.log([1, 2, 3].fill(4, 1, 1)); // [1, 2, 3] console.log([1, 2, 3].fill(4, 3, 3)); // [1, 2, 3] console.log([1, 2, 3].fill(4, -3, -2)); // [4, 2, 3] console.log([1, 2, 3].fill(4, NaN, NaN)); // [1, 2, 3] console.log([1, 2, 3].fill(4, 3, 5)); // [1, 2, 3] console.log(Array(3).fill(4)); // [4, 4, 4] // A single object, referenced by each slot of the array: const arr = Array(3).fill({}); // [{}, {}, {}] arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }] ``` ### Using fill() to create a matrix of all 1 This example shows how to create a matrix of all 1, like the `ones()` function of Octave or MATLAB. ```js const arr = new Array(3); for (let i = 0; i < arr.length; i++) { arr[i] = new Array(4).fill(1); // Creating an array of size 4 and filled of 1 } arr[0][0] = 10; console.log(arr[0][0]); // 10 console.log(arr[1][0]); // 1 console.log(arr[2][0]); // 1 ``` ### Using fill() to populate an empty array This example shows how to populate an array, setting all elements to a specific value. The `end` parameter does not have to be specified. ```js const tempGirls = Array(5).fill("girl", 0); ``` Note that the array was initially a [sparse array](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays) with no assigned indices. `fill()` is still able to fill this array. ### Calling fill() on non-array objects The `fill()` method reads the `length` property of `this` and sets the value of each integer-keyed property from `start` to `end`. ```js const arrayLike = { length: 2 }; console.log(Array.prototype.fill.call(arrayLike, 1)); // { '0': 1, '1': 1, length: 2 } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.prototype.fill` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("TypedArray.prototype.fill()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/tolocalestring/index.md
--- title: Array.prototype.toLocaleString() slug: Web/JavaScript/Reference/Global_Objects/Array/toLocaleString page-type: javascript-instance-method browser-compat: javascript.builtins.Array.toLocaleString --- {{JSRef}} The **`toLocaleString()`** method of {{jsxref("Array")}} instances returns a string representing the elements of the array. The elements are converted to strings using their `toLocaleString` methods and these strings are separated by a locale-specific string (such as a comma ","). {{EmbedInteractiveExample("pages/js/array-tolocalestring.html", "shorter")}} ## Syntax ```js-nolint toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters - `locales` {{optional_inline}} - : A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [the parameter description on the `Intl` main page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument). - `options` {{optional_inline}} - : An object with configuration properties. For numbers, see {{jsxref("Number.prototype.toLocaleString()")}}; for dates, see {{jsxref("Date.prototype.toLocaleString()")}}. ### Return value A string representing the elements of the array. ## Description The `Array.prototype.toLocaleString` method traverses its content, calling the `toLocaleString` method of every element with the `locales` and `options` parameters provided, and concatenates them with an implementation-defined separator (such as a comma ","). Note that the method itself does not consume the two parameters β€” it only passes them to the `toLocaleString()` of each element. The choice of the separator string depends on the host's current locale, not the `locales` parameter. If an element is `undefined`, `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. When used on [sparse arrays](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the `toLocaleString()` method iterates empty slots as if they have the value `undefined`. The `toLocaleString()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. ## Examples ### Using locales and options The elements of the array are converted to strings using their `toLocaleString` methods. - `Object`: {{jsxref("Object.prototype.toLocaleString()")}} - `Number`: {{jsxref("Number.prototype.toLocaleString()")}} - `Date`: {{jsxref("Date.prototype.toLocaleString()")}} Always display the currency for the strings and numbers in the `prices` array: ```js const prices = ["οΏ₯7", 500, 8123, 12]; prices.toLocaleString("ja-JP", { style: "currency", currency: "JPY" }); // "οΏ₯7,οΏ₯500,οΏ₯8,123,οΏ₯12" ``` For more examples, see also the [`Intl.NumberFormat`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) and [`Intl.DateTimeFormat`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) pages. ### Using toLocaleString() on sparse arrays `toLocaleString()` treats empty slots the same as `undefined` and produces an extra separator: ```js console.log([1, , 3].toLocaleString()); // '1,,3' ``` ### Calling toLocaleString() on non-array objects The `toLocaleString()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`. ```js const arrayLike = { length: 3, 0: 1, 1: 2, 2: 3, 3: 4, // ignored by toLocaleString() since length is 3 }; console.log(Array.prototype.toLocaleString.call(arrayLike)); // 1,2,3 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array.prototype.toString()")}} - {{jsxref("TypedArray.prototype.toLocaleString()")}} - {{jsxref("Intl")}} - {{jsxref("Intl.ListFormat")}} - {{jsxref("Object.prototype.toLocaleString()")}} - {{jsxref("Number.prototype.toLocaleString()")}} - {{jsxref("Date.prototype.toLocaleString()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/sort/index.md
--- title: Array.prototype.sort() slug: Web/JavaScript/Reference/Global_Objects/Array/sort page-type: javascript-instance-method browser-compat: javascript.builtins.Array.sort --- {{JSRef}} The **`sort()`** method of {{jsxref("Array")}} instances sorts the elements of an array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values. The time and space complexity of the sort cannot be guaranteed as it depends on the implementation. To sort the elements in an array without mutating the original array, use {{jsxref("Array/toSorted", "toSorted()")}}. {{EmbedInteractiveExample("pages/js/array-sort.html")}} ## Syntax ```js-nolint sort() sort(compareFn) ``` ### Parameters - `compareFn` {{optional_inline}} - : A function that defines the sort order. The return value should be a number whose sign indicates the relative order of the two elements: negative if `a` is less than `b`, positive if `a` is greater than `b`, and zero if they are equal. `NaN` is treated as `0`. The function is called with the following arguments: - `a` - : The first element for comparison. Will never be `undefined`. - `b` - : The second element for comparison. Will never be `undefined`. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value. ### Return value The reference to the original array, now sorted. Note that the array is sorted _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description If `compareFn` is not supplied, all non-`undefined` array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. All `undefined` elements are sorted to the end of the array. The `sort()` method preserves empty slots. If the source array is [sparse](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the empty slots are moved to the end of the array, and always come after all the `undefined`. > **Note:** In UTF-16, Unicode characters above `\uFFFF` are > encoded as two surrogate code units, of the range > `\uD800` - `\uDFFF`. The value of each code unit is taken > separately into account for the comparison. Thus the character formed by the surrogate > pair `\uD855\uDE51` will be sorted before the character > `\uFF3A`. If `compareFn` is supplied, all non-`undefined` array elements are sorted according to the return value of the compare function (all `undefined` elements are sorted to the end of the array, with no call to `compareFn`). | `compareFn(a, b)` return value | sort order | | ------------------------------ | ---------------------------------- | | > 0 | sort `a` after `b`, e.g. `[b, a]` | | < 0 | sort `a` before `b`, e.g. `[a, b]` | | === 0 | keep original order of `a` and `b` | So, the compare function has the following form: ```js-nolint function compareFn(a, b) { if (a is less than b by some ordering criterion) { return -1; } else if (a is greater than b by the ordering criterion) { return 1; } // a must be equal to b return 0; } ``` More formally, the comparator is expected to have the following properties, in order to ensure proper sort behavior: - _Pure_: The comparator does not mutate the objects being compared or any external state. (This is important because there's no guarantee _when_ and _how_ the comparator will be called, so any particular call should not produce visible effects to the outside.) - _Stable_: The comparator returns the same result with the same pair of input. - _Reflexive_: `compareFn(a, a) === 0`. - _Anti-symmetric_: `compareFn(a, b)` and `compareFn(b, a)` must both be `0` or have opposite signs. - _Transitive_: If `compareFn(a, b)` and `compareFn(b, c)` are both positive, zero, or negative, then `compareFn(a, c)` has the same positivity as the previous two. A comparator conforming to the constraints above will always be able to return all of `1`, `0`, and `-1`, or consistently return `0`. For example, if a comparator only returns `1` and `0`, or only returns `0` and `-1`, it will not be able to sort reliably because _anti-symmetry_ is broken. A comparator that always returns `0` will cause the array to not be changed at all, but is reliable nonetheless. The default lexicographic comparator satisfies all constraints above. To compare numbers instead of strings, the compare function can subtract `b` from `a`. The following function will sort the array in ascending order (if it doesn't contain `NaN`): ```js function compareNumbers(a, b) { return a - b; } ``` The `sort()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ## Examples ### Creating, displaying, and sorting an array The following example creates four arrays and displays the original array, then the sorted arrays. The numeric arrays are sorted without a compare function, then sorted using one. ```js const stringArray = ["Blue", "Humpback", "Beluga"]; const numberArray = [40, 1, 5, 200]; const numericStringArray = ["80", "9", "700"]; const mixedNumericArray = ["80", "9", "700", 40, 1, 5, 200]; function compareNumbers(a, b) { return a - b; } stringArray.join(); // 'Blue,Humpback,Beluga' stringArray.sort(); // ['Beluga', 'Blue', 'Humpback'] numberArray.join(); // '40,1,5,200' numberArray.sort(); // [1, 200, 40, 5] numberArray.sort(compareNumbers); // [1, 5, 40, 200] numericStringArray.join(); // '80,9,700' numericStringArray.sort(); // ['700', '80', '9'] numericStringArray.sort(compareNumbers); // ['9', '80', '700'] mixedNumericArray.join(); // '80,9,700,40,1,5,200' mixedNumericArray.sort(); // [1, 200, 40, 5, '700', '80', '9'] mixedNumericArray.sort(compareNumbers); // [1, 5, '9', 40, '80', 200, '700'] ``` ### Sorting array of objects Arrays of objects can be sorted by comparing the value of one of their properties. ```js const items = [ { name: "Edward", value: 21 }, { name: "Sharpe", value: 37 }, { name: "And", value: 45 }, { name: "The", value: -12 }, { name: "Magnetic", value: 13 }, { name: "Zeros", value: 37 }, ]; // sort by value items.sort((a, b) => a.value - b.value); // sort by name items.sort((a, b) => { const nameA = a.name.toUpperCase(); // ignore upper and lowercase const nameB = b.name.toUpperCase(); // ignore upper and lowercase if (nameA < nameB) { return -1; } if (nameA > nameB) { return 1; } // names must be equal return 0; }); ``` ### Sorting non-ASCII characters For sorting strings with non-{{Glossary("ASCII")}} characters, i.e. strings with accented characters (e, Γ©, Γ¨, a, Γ€, etc.), strings from languages other than English, use {{jsxref("String.prototype.localeCompare()")}}. This function can compare those characters so they appear in the right order. ```js const items = ["rΓ©servΓ©", "premier", "communiquΓ©", "cafΓ©", "adieu", "Γ©clair"]; items.sort((a, b) => a.localeCompare(b)); // items is ['adieu', 'cafΓ©', 'communiquΓ©', 'Γ©clair', 'premier', 'rΓ©servΓ©'] ``` ### Sorting with map The `compareFn` can be invoked multiple times per element within the array. Depending on the `compareFn`'s nature, this may yield a high overhead. The more work a `compareFn` does and the more elements there are to sort, it may be more efficient to use [`map()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) for sorting. The idea is to traverse the array once to extract the actual values used for sorting into a temporary array, sort the temporary array, and then traverse the temporary array to achieve the right order. ```js // the array to be sorted const data = ["delta", "alpha", "charlie", "bravo"]; // temporary array holds objects with position and sort-value const mapped = data.map((v, i) => { return { i, value: someSlowOperation(v) }; }); // sorting the mapped array containing the reduced values mapped.sort((a, b) => { if (a.value > b.value) { return 1; } if (a.value < b.value) { return -1; } return 0; }); const result = mapped.map((v) => data[v.i]); ``` There is an open source library available called [mapsort](https://github.com/Pimm/mapsort) which applies this approach. ### sort() returns the reference to the same array The `sort()` method returns a reference to the original array, so mutating the returned array will mutate the original array as well. ```js const numbers = [3, 1, 4, 1, 5]; const sorted = numbers.sort((a, b) => a - b); // numbers and sorted are both [1, 1, 3, 4, 5] sorted[0] = 10; console.log(numbers[0]); // 10 ``` In case you want `sort()` to not mutate the original array, but return a [shallow-copied](/en-US/docs/Glossary/Shallow_copy) array like other array methods (e.g. [`map()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)) do, use the {{jsxref("Array/toSorted", "toSorted()")}} method. Alternatively, you can do a shallow copy before calling `sort()`, using the [spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) or [`Array.from()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from). ```js const numbers = [3, 1, 4, 1, 5]; // [...numbers] creates a shallow copy, so sort() does not mutate the original const sorted = [...numbers].sort((a, b) => a - b); sorted[0] = 10; console.log(numbers[0]); // 3 ``` ### Sort stability Since version 10 (or ECMAScript 2019), the specification dictates that `Array.prototype.sort` is stable. For example, say you had a list of students alongside their grades. Note that the list of students is already pre-sorted by name in alphabetical order: ```js const students = [ { name: "Alex", grade: 15 }, { name: "Devlin", grade: 15 }, { name: "Eagle", grade: 13 }, { name: "Sam", grade: 14 }, ]; ``` After sorting this array by `grade` in ascending order: ```js students.sort((firstItem, secondItem) => firstItem.grade - secondItem.grade); ``` The `students` variable will then have the following value: ```js [ { name: "Eagle", grade: 13 }, { name: "Sam", grade: 14 }, { name: "Alex", grade: 15 }, // original maintained for similar grade (stable sorting) { name: "Devlin", grade: 15 }, // original maintained for similar grade (stable sorting) ]; ``` It's important to note that students that have the same grade (for example, Alex and Devlin), will remain in the same order as before calling the sort. This is what a stable sorting algorithm guarantees. Before version 10 (or ECMAScript 2019), sort stability was not guaranteed, meaning that you could end up with the following: ```js [ { name: "Eagle", grade: 13 }, { name: "Sam", grade: 14 }, { name: "Devlin", grade: 15 }, // original order not maintained { name: "Alex", grade: 15 }, // original order not maintained ]; ``` ### Sorting with non-well-formed comparator If a comparing function does not satisfy all of purity, stability, reflexivity, anti-symmetry, and transitivity rules, as explained in the [description](#description), the program's behavior is not well-defined. For example, consider this code: ```js const arr = [3, 1, 4, 1, 5, 9]; const compareFn = (a, b) => (a > b ? 1 : 0); arr.sort(compareFn); ``` The `compareFn` function here is not well-formed, because it does not satisfy anti-symmetry: if `a > b`, it returns `1`; but by swapping `a` and `b`, it returns `0` instead of a negative value. Therefore, the resulting array will be different across engines. For example, V8 (used by Chrome, Node.js, etc.) and JavaScriptCore (used by Safari) would not sort the array at all and return `[3, 1, 4, 1, 5, 9]`, while SpiderMonkey (used by Firefox) will return the array sorted ascendingly, as `[1, 1, 3, 4, 5, 9]`. However, if the `compareFn` function is changed slightly so that it returns `-1` or `0`: ```js const arr = [3, 1, 4, 1, 5, 9]; const compareFn = (a, b) => (a > b ? -1 : 0); arr.sort(compareFn); ``` Then V8 and JavaScriptCore sorts it descendingly, as `[9, 5, 4, 3, 1, 1]`, while SpiderMonkey returns it as-is: `[3, 1, 4, 1, 5, 9]`. Due to this implementation inconsistency, you are always advised to make your comparator well-formed by following the five constraints. ### Using sort() on sparse arrays Empty slots are moved to the end of the array. ```js console.log(["a", "c", , "b"].sort()); // ['a', 'b', 'c', empty] console.log([, undefined, "a", "b"].sort()); // ["a", "b", undefined, empty] ``` ### Calling sort() on non-array objects The `sort()` method reads the `length` property of `this`. It then collects all existing integer-keyed properties in the range of `0` to `length - 1`, sorts them, and writes them back. If there are missing properties in the range, the corresponding trailing properties are [deleted](/en-US/docs/Web/JavaScript/Reference/Operators/delete), as if the non-existent properties are sorted towards the end. ```js const arrayLike = { length: 3, unrelated: "foo", 0: 5, 2: 4, }; console.log(Array.prototype.sort.call(arrayLike)); // { '0': 4, '1': 5, length: 3, unrelated: 'foo' } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.prototype.sort` with modern behavior like stable sort in `core-js`](https://github.com/zloirock/core-js#ecmascript-array) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array.prototype.reverse()")}} - {{jsxref("Array.prototype.toSorted()")}} - {{jsxref("String.prototype.localeCompare()")}} - {{jsxref("TypedArray.prototype.sort()")}} - [Getting things sorted in V8](https://v8.dev/blog/array-sort) on v8.dev (2018) - [Stable `Array.prototype.sort`](https://v8.dev/features/stable-sort) on v8.dev (2019) - [`Array.prototype.sort` stability](https://mathiasbynens.be/demo/sort-stability) by Mathias Bynens
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/isarray/index.md
--- title: Array.isArray() slug: Web/JavaScript/Reference/Global_Objects/Array/isArray page-type: javascript-static-method browser-compat: javascript.builtins.Array.isArray --- {{JSRef}} The **`Array.isArray()`** static method determines whether the passed value is an {{jsxref("Array")}}. {{EmbedInteractiveExample("pages/js/array-isarray.html")}} ## Syntax ```js-nolint Array.isArray(value) ``` ### Parameters - `value` - : The value to be checked. ### Return value `true` if `value` is an {{jsxref("Array")}}; otherwise, `false`. `false` is always returned if `value` is a {{jsxref("TypedArray")}} instance. ## Description `Array.isArray()` checks if the passed value is an {{jsxref("Array")}}. It does not check the value's prototype chain, nor does it rely on the `Array` constructor it is attached to. It returns `true` for any value that was created using the array literal syntax or the `Array` constructor. This makes it safe to use with cross-realm objects, where the identity of the `Array` constructor is different and would therefore cause [`instanceof Array`](/en-US/docs/Web/JavaScript/Reference/Operators/instanceof) to fail. See the article ["Determining with absolute accuracy whether or not a JavaScript object is an array"](https://web.mit.edu/jwalden/www/isArray.html) for more details. `Array.isArray()` also rejects objects with `Array.prototype` in its prototype chain but aren't actual arrays, which `instanceof Array` would accept. ## Examples ### Using Array.isArray() ```js // all following calls return true Array.isArray([]); Array.isArray([1]); Array.isArray(new Array()); Array.isArray(new Array("a", "b", "c", "d")); Array.isArray(new Array(3)); // Little known fact: Array.prototype itself is an array: Array.isArray(Array.prototype); // all following calls return false Array.isArray(); Array.isArray({}); Array.isArray(null); Array.isArray(undefined); Array.isArray(17); Array.isArray("Array"); Array.isArray(true); Array.isArray(false); Array.isArray(new Uint8Array(32)); // This is not an array, because it was not created using the // array literal syntax or the Array constructor Array.isArray({ __proto__: Array.prototype }); ``` ### instanceof vs. Array.isArray() When checking for `Array` instance, `Array.isArray()` is preferred over `instanceof` because it works across realms. ```js const iframe = document.createElement("iframe"); document.body.appendChild(iframe); const xArray = window.frames[window.frames.length - 1].Array; const arr = new xArray(1, 2, 3); // [1, 2, 3] // Correctly checking for Array Array.isArray(arr); // true // The prototype of arr is xArray.prototype, which is a // different object from Array.prototype arr instanceof Array; // false ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.isArray` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/fromasync/index.md
--- title: Array.fromAsync() slug: Web/JavaScript/Reference/Global_Objects/Array/fromAsync page-type: javascript-static-method browser-compat: javascript.builtins.Array.fromAsync --- {{JSRef}} The **`Array.fromAsync()`** static method creates a new, shallow-copied `Array` instance from an [async iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols), [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol), or [array-like](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects) object. ## Syntax ```js-nolint Array.fromAsync(arrayLike) Array.fromAsync(arrayLike, mapFn) Array.fromAsync(arrayLike, mapFn, thisArg) ``` ### Parameters - `arrayLike` - : An async iterable, iterable, or array-like object to convert to an array. - `mapFn` {{optional_inline}} - : A function to call on every element of the array. If provided, every value to be added to the array is first passed through this function, and `mapFn`'s return value is added to the array instead (after being [awaited](/en-US/docs/Web/JavaScript/Reference/Operators/await)). The function is called with the following arguments: - `element` - : The current element being processed in the array. Because all elements are first [awaited](/en-US/docs/Web/JavaScript/Reference/Operators/await), this value will never be a [thenable](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables). - `index` - : The index of the current element being processed in the array. - `thisArg` {{optional_inline}} - : Value to use as `this` when executing `mapFn`. ### Return value A new {{jsxref("Promise")}} whose fulfillment value is a new {{jsxref("Array")}} instance. ## Description `Array.fromAsync()` lets you create arrays from: - [async iterable objects](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols) (objects such as {{domxref("ReadableStream")}} and {{jsxref("AsyncGenerator")}}); or, if the object is not async iterable, - [iterable objects](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (objects such as {{jsxref("Map")}} and {{jsxref("Set")}}); or, if the object is not iterable, - array-like objects (objects with a `length` property and indexed elements). `Array.fromAsync()` iterates the async iterable in a fashion very similar to {{jsxref("Statements/for-await...of", "for await...of")}}. `Array.fromAsync()` is almost equivalent to {{jsxref("Array.from()")}} in terms of behavior, except the following: - `Array.fromAsync()` handles async iterable objects. - `Array.fromAsync()` returns a {{jsxref("Promise")}} that fulfills to the array instance. - If `Array.fromAsync()` is called with a non-async iterable object, each element to be added to the array is first [awaited](/en-US/docs/Web/JavaScript/Reference/Operators/await). - If a `mapFn` is provided, its input and output are internally awaited. `Array.fromAsync()` and {{jsxref("Promise.all()")}} can both turn an iterable of promises into a promise of an array. However, there are two key differences: - `Array.fromAsync()` awaits each value yielded from the object sequentially. `Promise.all()` awaits all values concurrently. - `Array.fromAsync()` iterates the iterable lazily, and doesn't retrieve the next value until the current one is settled. `Promise.all()` retrieves all values in advance and awaits them all. ## Examples ### Array from an async iterable ```js const asyncIterable = (async function* () { for (let i = 0; i < 5; i++) { await new Promise((resolve) => setTimeout(resolve, 10 * i)); yield i; } })(); Array.fromAsync(asyncIterable).then((array) => console.log(array)); // [0, 1, 2, 3, 4] ``` ### Array from a sync iterable ```js Array.fromAsync( new Map([ [1, 2], [3, 4], ]), ).then((array) => console.log(array)); // [[1, 2], [3, 4]] ``` ### Array from a sync iterable that yields promises ```js Array.fromAsync( new Set([Promise.resolve(1), Promise.resolve(2), Promise.resolve(3)]), ).then((array) => console.log(array)); // [1, 2, 3] ``` ### Array from an array-like object of promises ```js Array.fromAsync({ length: 3, 0: Promise.resolve(1), 1: Promise.resolve(2), 2: Promise.resolve(3), }).then((array) => console.log(array)); // [1, 2, 3] ``` ### Using mapFn Both the input and output of `mapFn` are awaited internally by `Array.fromAsync()`. ```js function delayedValue(v) { return new Promise((resolve) => setTimeout(() => resolve(v), 100)); } Array.fromAsync( [delayedValue(1), delayedValue(2), delayedValue(3)], (element) => delayedValue(element * 2), ).then((array) => console.log(array)); // [2, 4, 6] ``` ### Comparison with Promise.all() `Array.fromAsync()` awaits each value yielded from the object sequentially. `Promise.all()` awaits all values concurrently. ```js function* makeIterableOfPromises() { for (let i = 0; i < 5; i++) { yield new Promise((resolve) => setTimeout(resolve, 100)); } } (async () => { console.time("Array.fromAsync() time"); await Array.fromAsync(makeIterableOfPromises()); console.timeEnd("Array.fromAsync() time"); // Array.fromAsync() time: 503.610ms console.time("Promise.all() time"); await Promise.all(makeIterableOfPromises()); console.timeEnd("Promise.all() time"); // Promise.all() time: 101.728ms })(); ``` ### No error handling for sync iterables Similar to [`for await...of`](/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of#iterating_over_sync_iterables_and_generators), if the object being iterated is a sync iterable, and an error is thrown while iterating, the `return()` method of the underlying iterator will not be called, so the iterator is not closed. ```js function* generatorWithRejectedPromises() { try { yield 0; yield Promise.reject(3); } finally { console.log("called finally"); } } (async () => { try { await Array.fromAsync(generatorWithRejectedPromises()); } catch (e) { console.log("caught", e); } })(); // caught 3 // No "called finally" message ``` If you need to close the iterator, you need to use a {{jsxref("Statements/for...of", "for...of")}} loop instead, and `await` each value yourself. ```js (async () => { const arr = []; try { for (const val of generatorWithRejectedPromises()) { arr.push(await val); } } catch (e) { console.log("caught", e); } })(); // called finally // caught 3 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.fromAsync` in `core-js`](https://github.com/zloirock/core-js#arrayfromasync) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array/Array", "Array()")}} - {{jsxref("Array.of()")}} - {{jsxref("Array.from()")}} - {{jsxref("Statements/for-await...of", "for await...of")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/join/index.md
--- title: Array.prototype.join() slug: Web/JavaScript/Reference/Global_Objects/Array/join page-type: javascript-instance-method browser-compat: javascript.builtins.Array.join --- {{JSRef}} The **`join()`** method of {{jsxref("Array")}} instances creates and returns a new string by concatenating all of the elements in this array, separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator. {{EmbedInteractiveExample("pages/js/array-join.html")}} ## Syntax ```js-nolint join() join(separator) ``` ### Parameters - `separator` {{optional_inline}} - : A string to separate each pair of adjacent elements of the array. If omitted, the array elements are separated with a comma (","). ### Return value A string with all array elements joined. If `array.length` is `0`, the empty string is returned. ## Description The string conversions of all array elements are joined into one string. If an element is `undefined` or `null`, it is converted to an empty string instead of the string `"null"` or `"undefined"`. The `join` method is accessed internally by [`Array.prototype.toString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString) with no arguments. Overriding `join` of an array instance will override its `toString` behavior as well. `Array.prototype.join` recursively converts each element, including other arrays, to strings. Because the string returned by `Array.prototype.toString` (which is the same as calling `join()`) does not have delimiters, nested arrays look like they are flattened. You can only control the separator of the first level, while deeper levels always use the default comma. ```js const matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]; console.log(matrix.join()); // 1,2,3,4,5,6,7,8,9 console.log(matrix.join(";")); // 1,2,3;4,5,6;7,8,9 ``` When an array is cyclic (it contains an element that is itself), browsers avoid infinite recursion by ignoring the cyclic reference. ```js const arr = []; arr.push(1, [3, arr, 4], 2); console.log(arr.join(";")); // 1;3,,4;2 ``` When used on [sparse arrays](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the `join()` method iterates empty slots as if they have the value `undefined`. The `join()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. ## Examples ### Joining an array four different ways The following example creates an array, `a`, with three elements, then joins the array four times: using the default separator, then a comma and a space, then a plus and an empty string. ```js const a = ["Wind", "Water", "Fire"]; a.join(); // 'Wind,Water,Fire' a.join(", "); // 'Wind, Water, Fire' a.join(" + "); // 'Wind + Water + Fire' a.join(""); // 'WindWaterFire' ``` ### Using join() on sparse arrays `join()` treats empty slots the same as `undefined` and produces an extra separator: ```js console.log([1, , 3].join()); // '1,,3' console.log([1, undefined, 3].join()); // '1,,3' ``` ### Calling join() on non-array objects The `join()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`. ```js const arrayLike = { length: 3, 0: 2, 1: 3, 2: 4, 3: 5, // ignored by join() since length is 3 }; console.log(Array.prototype.join.call(arrayLike)); // 2,3,4 console.log(Array.prototype.join.call(arrayLike, ".")); // 2.3.4 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.prototype.join` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array.prototype.toString()")}} - {{jsxref("TypedArray.prototype.join()")}} - {{jsxref("String.prototype.split()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/@@species/index.md
--- title: Array[@@species] slug: Web/JavaScript/Reference/Global_Objects/Array/@@species page-type: javascript-static-accessor-property browser-compat: javascript.builtins.Array.@@species --- {{JSRef}} The **`Array[@@species]`** static accessor property returns the constructor used to construct return values from array 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. Modern array methods, such as {{jsxref("Array/toReversed", "toReversed()")}}, do not use `@@species` and always return a new `Array` base class instance. ## Syntax ```js-nolint Array[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 methods that create new arrays. ## Description The `@@species` accessor property returns the default constructor for `Array` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Array { 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 SubArray extends Array {} SubArray[Symbol.species] === SubArray; // true ``` When calling array methods that do not mutate the existing array but return a new array instance (for example, [`filter()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) and [`map()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)), the array's `constructor[@@species]` will be accessed. The returned constructor will be used to construct the return value of the array method. This makes it technically possible to make array methods return objects unrelated to arrays. ```js class NotAnArray { constructor(length) { this.length = length; } } const arr = [0, 1, 2]; arr.constructor = { [Symbol.species]: NotAnArray }; arr.map((i) => i); // NotAnArray { '0': 0, '1': 1, '2': 2, length: 3 } arr.filter((i) => i); // NotAnArray { '0': 1, '1': 2, length: 0 } arr.concat([1, 2]); // NotAnArray { '0': 0, '1': 1, '2': 2, '3': 1, '4': 2, length: 5 } ``` ## Examples ### Species in ordinary objects The `@@species` property returns the default constructor function, which is the `Array` constructor for `Array`. ```js Array[Symbol.species]; // [Function: Array] ``` ### Species in derived objects In an instance of a custom `Array` subclass, such as `MyArray`, the `MyArray` species is the `MyArray` constructor. However, you might want to overwrite this, in order to return parent `Array` objects in your derived class methods: ```js class MyArray extends Array { // Overwrite MyArray species to the parent Array constructor static get [Symbol.species]() { return Array; } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array[@@species]` and support of `@@species` in all affected `Array` methods in `core-js`](https://github.com/zloirock/core-js#ecmascript-array) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Symbol.species")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/indexof/index.md
--- title: Array.prototype.indexOf() slug: Web/JavaScript/Reference/Global_Objects/Array/indexOf page-type: javascript-instance-method browser-compat: javascript.builtins.Array.indexOf --- {{JSRef}} The **`indexOf()`** method of {{jsxref("Array")}} instances returns the first index at which a given element can be found in the array, or -1 if it is not present. {{EmbedInteractiveExample("pages/js/array-indexof.html")}} ## Syntax ```js-nolint indexOf(searchElement) indexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the array. - `fromIndex` {{optional_inline}} - : Zero-based index at which to start searching, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). - Negative index counts back from the end of the array β€” if `-array.length <= fromIndex < 0`, `fromIndex + array.length` is used. Note, the array is still searched from front to back in this case. - If `fromIndex < -array.length` or `fromIndex` is omitted, `0` is used, causing the entire array to be searched. - If `fromIndex >= array.length`, the array is not searched and `-1` is returned. ### Return value The first index of `searchElement` in the array; `-1` if not found. ## Description The `indexOf()` method compares `searchElement` to elements of the array using [strict equality](/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality) (the same algorithm used by the `===` operator). [`NaN`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN) values are never compared as equal, so `indexOf()` always returns `-1` when `searchElement` is `NaN`. The `indexOf()` method skips empty slots in [sparse arrays](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays). The `indexOf()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. ## Examples ### Using indexOf() The following example uses `indexOf()` to locate values in an array. ```js const array = [2, 9, 9]; array.indexOf(2); // 0 array.indexOf(7); // -1 array.indexOf(9, 2); // 2 array.indexOf(2, -1); // -1 array.indexOf(2, -3); // 0 ``` You cannot use `indexOf()` to search for `NaN`. ```js const array = [NaN]; array.indexOf(NaN); // -1 ``` ### Finding all the occurrences of an element ```js const indices = []; const array = ["a", "b", "a", "c", "a", "d"]; const element = "a"; let idx = array.indexOf(element); while (idx !== -1) { indices.push(idx); idx = array.indexOf(element, idx + 1); } console.log(indices); // [0, 2, 4] ``` ### Finding if an element exists in the array or not and updating the array ```js function updateVegetablesCollection(veggies, veggie) { if (veggies.indexOf(veggie) === -1) { veggies.push(veggie); console.log(`New veggies collection is: ${veggies}`); } else { console.log(`${veggie} already exists in the veggies collection.`); } } const veggies = ["potato", "tomato", "chillies", "green-pepper"]; updateVegetablesCollection(veggies, "spinach"); // New veggies collection is: potato,tomato,chillies,green-pepper,spinach updateVegetablesCollection(veggies, "spinach"); // spinach already exists in the veggies collection. ``` ### Using indexOf() on sparse arrays You cannot use `indexOf()` to search for empty slots in sparse arrays. ```js console.log([1, , 3].indexOf(undefined)); // -1 ``` ### Calling indexOf() on non-array objects The `indexOf()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`. ```js const arrayLike = { length: 3, 0: 2, 1: 3, 2: 4, 3: 5, // ignored by indexOf() since length is 3 }; console.log(Array.prototype.indexOf.call(arrayLike, 2)); // 0 console.log(Array.prototype.indexOf.call(arrayLike, 5)); // -1 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.prototype.indexOf` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array.prototype.findIndex()")}} - {{jsxref("Array.prototype.findLastIndex()")}} - {{jsxref("Array.prototype.lastIndexOf()")}} - {{jsxref("TypedArray.prototype.indexOf()")}} - {{jsxref("String.prototype.indexOf()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/splice/index.md
--- title: Array.prototype.splice() slug: Web/JavaScript/Reference/Global_Objects/Array/splice page-type: javascript-instance-method browser-compat: javascript.builtins.Array.splice --- {{JSRef}} The **`splice()`** method of {{jsxref("Array")}} instances changes the contents of an array by removing or replacing existing elements and/or adding new elements [in place](https://en.wikipedia.org/wiki/In-place_algorithm). To create a new array with a segment removed and/or replaced without mutating the original array, use {{jsxref("Array/toSpliced", "toSpliced()")}}. To access part of an array without modifying it, see {{jsxref("Array/slice", "slice()")}}. {{EmbedInteractiveExample("pages/js/array-splice.html")}} ## Syntax ```js-nolint splice(start) splice(start, deleteCount) splice(start, deleteCount, item1) splice(start, deleteCount, item1, item2) splice(start, deleteCount, item1, item2, /* …, */ itemN) ``` ### Parameters - `start` - : Zero-based index at which to start changing the array, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). - Negative index counts back from the end of the array β€” if `-array.length <= start < 0`, `start + array.length` is used. - If `start < -array.length`, `0` is used. - If `start >= array.length`, no element will be deleted, but the method will behave as an adding function, adding as many elements as provided. - If `start` is omitted (and `splice()` is called with no arguments), nothing is deleted. This is different from passing `undefined`, which is converted to `0`. - `deleteCount` {{optional_inline}} - : An integer indicating the number of elements in the array to remove from `start`. If `deleteCount` is omitted, or if its value is greater than or equal to the number of elements after the position specified by `start`, then all the elements from `start` to the end of the array will be deleted. However, if you wish to pass any `itemN` parameter, you should pass `Infinity` as `deleteCount` to delete all elements after `start`, because an explicit `undefined` gets [converted](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion) to `0`. If `deleteCount` is `0` or negative, no elements are removed. In this case, you should specify at least one new element (see below). - `item1`, …, `itemN` {{optional_inline}} - : The elements to add to the array, beginning from `start`. If you do not specify any elements, `splice()` will only remove elements from the array. ### Return value An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned. ## Description The `splice()` method is a [mutating method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#copying_methods_and_mutating_methods). It may change the content of `this`. If the specified number of elements to insert differs from the number of elements being removed, the array's `length` will be changed as well. At the same time, it uses [`@@species`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@species) to create a new array instance to be returned. If the deleted portion is [sparse](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the array returned by `splice()` is sparse as well, with those corresponding indices being empty slots. The `splice()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable. ## Examples ### Remove 0 (zero) elements before index 2, and insert "drum" ```js const myFish = ["angel", "clown", "mandarin", "sturgeon"]; const removed = myFish.splice(2, 0, "drum"); // myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"] // removed is [], no elements removed ``` ### Remove 0 (zero) elements before index 2, and insert "drum" and "guitar" ```js const myFish = ["angel", "clown", "mandarin", "sturgeon"]; const removed = myFish.splice(2, 0, "drum", "guitar"); // myFish is ["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"] // removed is [], no elements removed ``` ### Remove 0 (zero) elements at index 0, and insert "angel" `splice(0, 0, ...elements)` inserts elements at the start of the array like {{jsxref("Array/unshift", "unshift()")}}. ```js const myFish = ["clown", "mandarin", "sturgeon"]; const removed = myFish.splice(0, 0, "angel"); // myFish is ["angel", "clown", "mandarin", "sturgeon"] // no items removed ``` ### Remove 0 (zero) elements at last index, and insert "sturgeon" `splice(array.length, 0, ...elements)` inserts elements at the end of the array like {{jsxref("Array/push", "push()")}}. ```js const myFish = ["angel", "clown", "mandarin"]; const removed = myFish.splice(myFish.length, 0, "sturgeon"); // myFish is ["angel", "clown", "mandarin", "sturgeon"] // no items removed ``` ### Remove 1 element at index 3 ```js const myFish = ["angel", "clown", "drum", "mandarin", "sturgeon"]; const removed = myFish.splice(3, 1); // myFish is ["angel", "clown", "drum", "sturgeon"] // removed is ["mandarin"] ``` ### Remove 1 element at index 2, and insert "trumpet" ```js const myFish = ["angel", "clown", "drum", "sturgeon"]; const removed = myFish.splice(2, 1, "trumpet"); // myFish is ["angel", "clown", "trumpet", "sturgeon"] // removed is ["drum"] ``` ### Remove 2 elements from index 0, and insert "parrot", "anemone" and "blue" ```js const myFish = ["angel", "clown", "trumpet", "sturgeon"]; const removed = myFish.splice(0, 2, "parrot", "anemone", "blue"); // myFish is ["parrot", "anemone", "blue", "trumpet", "sturgeon"] // removed is ["angel", "clown"] ``` ### Remove 2 elements, starting from index 2 ```js const myFish = ["parrot", "anemone", "blue", "trumpet", "sturgeon"]; const removed = myFish.splice(2, 2); // myFish is ["parrot", "anemone", "sturgeon"] // removed is ["blue", "trumpet"] ``` ### Remove 1 element from index -2 ```js const myFish = ["angel", "clown", "mandarin", "sturgeon"]; const removed = myFish.splice(-2, 1); // myFish is ["angel", "clown", "sturgeon"] // removed is ["mandarin"] ``` ### Remove all elements, starting from index 2 ```js const myFish = ["angel", "clown", "mandarin", "sturgeon"]; const removed = myFish.splice(2); // myFish is ["angel", "clown"] // removed is ["mandarin", "sturgeon"] ``` ### Using splice() on sparse arrays The `splice()` method preserves the array's sparseness. ```js const arr = [1, , 3, 4, , 6]; console.log(arr.splice(1, 2)); // [empty, 3] console.log(arr); // [1, 4, empty, 6] ``` ### Calling splice() on non-array objects The `splice()` method reads the `length` property of `this`. It then updates the integer-keyed properties and the `length` property as needed. ```js const arrayLike = { length: 3, unrelated: "foo", 0: 5, 2: 4, }; console.log(Array.prototype.splice.call(arrayLike, 0, 1, 2, 3)); // [ 5 ] console.log(arrayLike); // { '0': 2, '1': 3, '3': 4, length: 4, unrelated: 'foo' } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array.prototype.concat()")}} - {{jsxref("Array.prototype.push()")}} - {{jsxref("Array.prototype.pop()")}} - {{jsxref("Array.prototype.shift()")}} - {{jsxref("Array.prototype.slice()")}} - {{jsxref("Array.prototype.toSpliced()")}} - {{jsxref("Array.prototype.unshift()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/filter/index.md
--- title: Array.prototype.filter() slug: Web/JavaScript/Reference/Global_Objects/Array/filter page-type: javascript-instance-method browser-compat: javascript.builtins.Array.filter --- {{JSRef}} The **`filter()`** method of {{jsxref("Array")}} instances creates a [shallow copy](/en-US/docs/Glossary/Shallow_copy) of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function. {{EmbedInteractiveExample("pages/js/array-filter.html", "shorter")}} ## Syntax ```js-nolint filter(callbackFn) filter(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the array. It should return a [truthy](/en-US/docs/Glossary/Truthy) value to keep the element in the resulting array, and a [falsy](/en-US/docs/Glossary/Falsy) value otherwise. 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. - `array` - : The array `filter()` was called upon. - `thisArg` {{optional_inline}} - : A value to use as `this` when executing `callbackFn`. See [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). ### Return value A [shallow copy](/en-US/docs/Glossary/Shallow_copy) of the given array containing just the elements that pass the test. If no elements pass the test, an empty array is returned. ## Description The `filter()` method is an [iterative method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). It calls a provided `callbackFn` function once for each element in an array, and constructs a new array of all the values for which `callbackFn` returns a [truthy](/en-US/docs/Glossary/Truthy) value. Array elements which do not pass the `callbackFn` test are not included in the new array. Read the [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods) section for more information about how these methods work in general. `callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in [sparse arrays](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays). The `filter()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. ## Examples ### Filtering out all small values The following example uses `filter()` to create a filtered array that has all elements with values less than 10 removed. ```js function isBigEnough(value) { return value >= 10; } const filtered = [12, 5, 8, 130, 44].filter(isBigEnough); // filtered is [12, 130, 44] ``` ### Find all prime numbers in an array The following example returns all prime numbers in the array: ```js const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]; function isPrime(num) { for (let i = 2; num > i; i++) { if (num % i === 0) { return false; } } return num > 1; } console.log(array.filter(isPrime)); // [2, 3, 5, 7, 11, 13] ``` ### Filtering invalid entries from JSON The following example uses `filter()` to create a filtered JSON of all elements with non-zero, numeric `id`. ```js const arr = [ { id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }, {}, { id: null }, { id: NaN }, { id: "undefined" }, ]; let invalidEntries = 0; function filterByID(item) { if (Number.isFinite(item.id) && item.id !== 0) { return true; } invalidEntries++; return false; } const arrByID = arr.filter(filterByID); console.log("Filtered Array\n", arrByID); // Filtered Array // [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }] console.log("Number of Invalid Entries =", invalidEntries); // Number of Invalid Entries = 5 ``` ### Searching in array Following example uses `filter()` to filter array content based on search criteria. ```js const fruits = ["apple", "banana", "grapes", "mango", "orange"]; /** * Filter array items based on search criteria (query) */ function filterItems(arr, query) { return arr.filter((el) => el.toLowerCase().includes(query.toLowerCase())); } console.log(filterItems(fruits, "ap")); // ['apple', 'grapes'] console.log(filterItems(fruits, "an")); // ['banana', 'mango', 'orange'] ``` ### Using the third argument of callbackFn The `array` argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses `map()` to extract the numerical ID from each name and then uses `filter()` to select the ones that are greater than its neighbors. ```js const names = ["JC63", "Bob132", "Ursula89", "Ben96"]; const greatIDs = names .map((name) => parseInt(name.match(/[0-9]+/)[0], 10)) .filter((id, idx, arr) => { // Without the arr argument, there's no way to easily access the // intermediate array without saving it to a variable. if (idx > 0 && id <= arr[idx - 1]) return false; if (idx < arr.length - 1 && id <= arr[idx + 1]) return false; return true; }); console.log(greatIDs); // [132, 96] ``` The `array` argument is _not_ the array that is being built β€” there is no way to access the array being built from the callback function. ### Using filter() on sparse arrays `filter()` will skip empty slots. ```js console.log([1, , undefined].filter((x) => x === undefined)); // [undefined] console.log([1, , undefined].filter((x) => x !== 2)); // [1, undefined] ``` ### Calling filter() on non-array objects The `filter()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`. ```js const arrayLike = { length: 3, 0: "a", 1: "b", 2: "c", 3: "a", // ignored by filter() since length is 3 }; console.log(Array.prototype.filter.call(arrayLike, (x) => x <= "b")); // [ 'a', 'b' ] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.prototype.filter` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array.prototype.forEach()")}} - {{jsxref("Array.prototype.every()")}} - {{jsxref("Array.prototype.map()")}} - {{jsxref("Array.prototype.some()")}} - {{jsxref("Array.prototype.reduce()")}} - {{jsxref("TypedArray.prototype.filter()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array
data/mdn-content/files/en-us/web/javascript/reference/global_objects/array/entries/index.md
--- title: Array.prototype.entries() slug: Web/JavaScript/Reference/Global_Objects/Array/entries page-type: javascript-instance-method browser-compat: javascript.builtins.Array.entries --- {{JSRef}} The **`entries()`** method of {{jsxref("Array")}} instances returns a new _[array iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator)_ object that contains the key/value pairs for each index in the array. {{EmbedInteractiveExample("pages/js/array-entries.html")}} ## Syntax ```js-nolint entries() ``` ### Parameters None. ### Return value A new [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator). ## Description When used on [sparse arrays](/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays), the `entries()` method iterates empty slots as if they have the value `undefined`. The `entries()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. ## Examples ### Iterating with index and element ```js const a = ["a", "b", "c"]; for (const [index, element] of a.entries()) { console.log(index, element); } // 0 'a' // 1 'b' // 2 'c' ``` ### Using a for...of loop ```js const array = ["a", "b", "c"]; const arrayEntries = array.entries(); for (const element of arrayEntries) { console.log(element); } // [0, 'a'] // [1, 'b'] // [2, 'c'] ``` ### Iterating sparse arrays `entries()` will visit empty slots as if they are `undefined`. ```js for (const element of [, "a"].entries()) { console.log(element); } // [0, undefined] // [1, 'a'] ``` ### Calling entries() on non-array objects The `entries()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`. ```js const arrayLike = { length: 3, 0: "a", 1: "b", 2: "c", 3: "d", // ignored by entries() since length is 3 }; for (const entry of Array.prototype.entries.call(arrayLike)) { console.log(entry); } // [ 0, 'a' ] // [ 1, 'b' ] // [ 2, 'c' ] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Array.prototype.entries` in `core-js`](https://github.com/zloirock/core-js#ecmascript-array) - [Indexed collections](/en-US/docs/Web/JavaScript/Guide/Indexed_collections) guide - {{jsxref("Array")}} - {{jsxref("Array.prototype.keys()")}} - {{jsxref("Array.prototype.values()")}} - [`Array.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@iterator) - {{jsxref("TypedArray.prototype.entries()")}} - [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typeerror/index.md
--- title: TypeError slug: Web/JavaScript/Reference/Global_Objects/TypeError page-type: javascript-class browser-compat: javascript.builtins.TypeError --- {{JSRef}} The **`TypeError`** object represents an error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type. A `TypeError` may be thrown when: - an operand or argument passed to a function is incompatible with the type expected by that operator or function; or - when attempting to modify a value that cannot be changed; or - when attempting to use a value in an inappropriate way. `TypeError` 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()")}}. `TypeError` is a subclass of {{jsxref("Error")}}. ## Constructor - {{jsxref("TypeError/TypeError", "TypeError()")}} - : Creates a new `TypeError` object. ## Instance properties _Also inherits instance properties from its parent {{jsxref("Error")}}_. These properties are defined on `TypeError.prototype` and shared by all `TypeError` instances. - {{jsxref("Object/constructor", "TypeError.prototype.constructor")}} - : The constructor function that created the instance object. For `TypeError` instances, the initial value is the {{jsxref("TypeError/TypeError", "TypeError")}} constructor. - {{jsxref("Error/name", "TypeError.prototype.name")}} - : Represents the name for the type of error. For `TypeError.prototype.name`, the initial value is `"TypeError"`. ## Instance methods _Inherits instance methods from its parent {{jsxref("Error")}}_. ## Examples ### Catching a TypeError ```js try { null.f(); } catch (e) { console.log(e instanceof TypeError); // true console.log(e.message); // "null has no properties" console.log(e.name); // "TypeError" console.log(e.stack); // Stack of the error } ``` ### Creating a TypeError ```js try { throw new TypeError("Hello"); } catch (e) { console.log(e instanceof TypeError); // true console.log(e.message); // "Hello" console.log(e.name); // "TypeError" 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/typeerror
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typeerror/typeerror/index.md
--- title: TypeError() constructor slug: Web/JavaScript/Reference/Global_Objects/TypeError/TypeError page-type: javascript-constructor browser-compat: javascript.builtins.TypeError.TypeError --- {{JSRef}} The **`TypeError()`** constructor creates {{jsxref("TypeError")}} objects. ## Syntax ```js-nolint new TypeError() new TypeError(message) new TypeError(message, options) new TypeError(message, fileName) new TypeError(message, fileName, lineNumber) TypeError() TypeError(message) TypeError(message, options) TypeError(message, fileName) TypeError(message, fileName, lineNumber) ``` > **Note:** `TypeError()` can be called with or without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Both create a new `TypeError` 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 TypeError ```js try { null.f(); } catch (e) { console.log(e instanceof TypeError); // true console.log(e.message); // "null has no properties" console.log(e.name); // "TypeError" console.log(e.stack); // Stack of the error } ``` ### Creating a TypeError ```js try { throw new TypeError("Hello"); } catch (e) { console.log(e instanceof TypeError); // true console.log(e.message); // "Hello" console.log(e.name); // "TypeError" 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/nan/index.md
--- title: NaN slug: Web/JavaScript/Reference/Global_Objects/NaN page-type: javascript-global-property browser-compat: javascript.builtins.NaN --- {{jsSidebar("Objects")}} The **`NaN`** global property is a value representing Not-A-Number. {{EmbedInteractiveExample("pages/js/globalprops-nan.html")}} ## Value The same number value as {{jsxref("Number.NaN")}}. {{js_property_attributes(0, 0, 0)}} ## Description `NaN` is a property of the _global object_. In other words, it is a variable in global scope. In modern browsers, `NaN` is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it. There are five different types of operations that return `NaN`: - Failed number conversion (e.g. explicit ones like `parseInt("blabla")`, `Number(undefined)`, or implicit ones like `Math.abs(undefined)`) - Math operation where the result is not a real number (e.g. `Math.sqrt(-1)`) - Indeterminate form (e.g. `0 * Infinity`, `1 ** Infinity`, `Infinity / Infinity`, `Infinity - Infinity`) - A method or expression whose operand is or gets coerced to `NaN` (e.g. `7 ** NaN`, `7 * "blabla"`) β€” this means `NaN` is contagious - Other cases where an invalid value is to be represented as a number (e.g. an invalid [Date](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) `new Date("blabla").getTime()`, `"".charCodeAt(1)`) `NaN` and its behaviors are not invented by JavaScript. Its semantics in floating point arithmetic (including that `NaN !== NaN`) are specified by [IEEE 754](https://en.wikipedia.org/wiki/Double_precision_floating-point_format). `NaN`'s behaviors include: - If `NaN` is involved in a mathematical operation (but not [bitwise operations](/en-US/docs/Web/JavaScript/Reference/Operators#bitwise_shift_operators)), the result is usually also `NaN`. (See [counter-example](#silently_escaping_nan) below.) - When `NaN` is one of the operands of any relational comparison (`>`, `<`, `>=`, `<=`), the result is always `false`. - `NaN` compares unequal (via [`==`](/en-US/docs/Web/JavaScript/Reference/Operators/Equality), [`!=`](/en-US/docs/Web/JavaScript/Reference/Operators/Inequality), [`===`](/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality), and [`!==`](/en-US/docs/Web/JavaScript/Reference/Operators/Strict_inequality)) to any other value β€” including to another `NaN` value. `NaN` is also one of the [falsy](/en-US/docs/Glossary/Falsy) values in JavaScript. ## Examples ### Testing against NaN To tell if a value is `NaN`, use {{jsxref("Number.isNaN()")}} or {{jsxref("isNaN()")}} to most clearly determine whether a value is `NaN` β€” or, since `NaN` is the only value that compares unequal to itself, you can perform a self-comparison like `x !== x`. ```js NaN === NaN; // false Number.NaN === NaN; // false isNaN(NaN); // true isNaN(Number.NaN); // true Number.isNaN(NaN); // true function valueIsNaN(v) { return v !== v; } valueIsNaN(1); // false valueIsNaN(NaN); // true valueIsNaN(Number.NaN); // true ``` However, do note the difference between `isNaN()` and `Number.isNaN()`: the former will return `true` if the value is currently `NaN`, or if it is going to be `NaN` after it is coerced to a number, while the latter will return `true` only if the value is currently `NaN`: ```js isNaN("hello world"); // true Number.isNaN("hello world"); // false ``` For the same reason, using a BigInt value will throw an error with `isNaN()` and not with `Number.isNaN()`: ```js isNaN(1n); // TypeError: Conversion from 'BigInt' to 'number' is not allowed. Number.isNaN(1n); // false ``` Additionally, some array methods cannot find `NaN`, while others can. Namely, the index-finding ones ({{jsxref("Array/indexOf", "indexOf()")}}, {{jsxref("Array/lastIndexOf", "lastIndexOf()")}}) cannot find `NaN`, while the value-finding ones ({{jsxref("Array/includes", "includes()")}}) can: ```js const arr = [2, 4, NaN, 12]; arr.indexOf(NaN); // -1 arr.includes(NaN); // true // Methods accepting a properly defined predicate can always find NaN arr.findIndex((n) => Number.isNaN(n)); // 2 ``` For more information about `NaN` and its comparison, see [Equality comparison and sameness](/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness). ### Observably distinct NaN values There's a motivation for `NaN` being unequal to itself. It's possible to produce two floating point numbers with different binary representations but are both `NaN`, because in [IEEE 754 encoding](https://en.wikipedia.org/wiki/NaN#Floating_point), any floating point number with exponent `0x7ff` and a non-zero mantissa is `NaN`. In JavaScript, you can do bit-level manipulation using [typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays). ```js const f2b = (x) => new Uint8Array(new Float64Array([x]).buffer); const b2f = (x) => new Float64Array(x.buffer)[0]; // Get a byte representation of NaN const n = f2b(NaN); const m = f2b(NaN); // Change the sign bit, which doesn't matter for NaN n[7] += 2 ** 7; // n[0] += 2**7; for big endian processors const nan2 = b2f(n); console.log(nan2); // NaN console.log(Object.is(nan2, NaN)); // true console.log(f2b(NaN)); // Uint8Array(8) [0, 0, 0, 0, 0, 0, 248, 127] console.log(f2b(nan2)); // Uint8Array(8) [0, 0, 0, 0, 0, 0, 248, 255] // Change the first bit, which is the least significant bit of the mantissa and doesn't matter for NaN m[0] = 1; // m[7] = 1; for big endian processors const nan3 = b2f(m); console.log(nan3); // NaN console.log(Object.is(nan3, NaN)); // true console.log(f2b(NaN)); // Uint8Array(8) [0, 0, 0, 0, 0, 0, 248, 127] console.log(f2b(nan3)); // Uint8Array(8) [1, 0, 0, 0, 0, 0, 248, 127] ``` ### Silently escaping NaN `NaN` propagates through mathematical operations, so it's usually sufficient to test for `NaN` once at the end of calculation to detect error conditions. The only case where `NaN` gets silently escaped is when using [exponentiation](/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation) with an exponent of `0`, which immediately returns `1` without testing the base's value. ```js NaN ** 0 === 1; // true ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Number.NaN")}} - {{jsxref("Number.isNaN()")}} - {{jsxref("isNaN()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/index.md
--- title: TypedArray slug: Web/JavaScript/Reference/Global_Objects/TypedArray page-type: javascript-class browser-compat: javascript.builtins.TypedArray --- {{JSRef}} A **_TypedArray_** object describes an array-like view of an underlying [binary data buffer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). There is no global property named `TypedArray`, nor is there a directly visible `TypedArray` constructor. Instead, there are a number of different global properties, whose values are typed array constructors for specific element types, listed below. On the following pages you will find common properties and methods that can be used with any typed array containing elements of any type. {{EmbedInteractiveExample("pages/js/typedarray-constructor.html")}} ## Description The `TypedArray` constructor (often referred to as `%TypedArray%` to indicate its "intrinsicness", since it does not correspond to any global exposed to a JavaScript program) serves as the common superclass of all `TypedArray` subclasses. Think about `%TypedArray%` as an "abstract class" providing a common interface of utility methods for all typed array subclasses. This constructor is not directly exposed: there is no global `TypedArray` property. It is only accessible through `Object.getPrototypeOf(Int8Array)` and similar. When creating an instance of a `TypedArray` subclass (e.g. `Int8Array`), an array buffer is created internally in memory or, if an `ArrayBuffer` object is given as constructor argument, that `ArrayBuffer` is used instead. The buffer address is saved as an internal property of the instance and all the methods of `%TypedArray%.prototype` will set and get values based on that array buffer address. ### TypedArray objects | Type | Value Range | Size in bytes | Web IDL type | | ------------------------------- | ------------------------------------- | ------------- | --------------------- | | {{jsxref("Int8Array")}} | -128 to 127 | 1 | `byte` | | {{jsxref("Uint8Array")}} | 0 to 255 | 1 | `octet` | | {{jsxref("Uint8ClampedArray")}} | 0 to 255 | 1 | `octet` | | {{jsxref("Int16Array")}} | -32768 to 32767 | 2 | `short` | | {{jsxref("Uint16Array")}} | 0 to 65535 | 2 | `unsigned short` | | {{jsxref("Int32Array")}} | -2147483648 to 2147483647 | 4 | `long` | | {{jsxref("Uint32Array")}} | 0 to 4294967295 | 4 | `unsigned long` | | {{jsxref("Float32Array")}} | `-3.4e38` to `3.4e38` | 4 | `unrestricted float` | | {{jsxref("Float64Array")}} | `-1.8e308` to `1.8e308` | 8 | `unrestricted double` | | {{jsxref("BigInt64Array")}} | -2<sup>63</sup> to 2<sup>63</sup> - 1 | 8 | `bigint` | | {{jsxref("BigUint64Array")}} | 0 to 2<sup>64</sup> - 1 | 8 | `bigint` | ### Value encoding and normalization All typed arrays operate on `ArrayBuffer`s, where you can observe the exact byte representation of each element, so how the numbers are encoded in binary format is significant. - Unsigned integer arrays (`Uint8Array`, `Uint16Array`, `Uint32Array`, and `BigUint64Array`) store the number directly in binary. - Signed integer arrays (`Int8Array`, `Int16Array`, `Int32Array`, and `BigInt64Array`) store the number using [two's complement](https://en.wikipedia.org/wiki/Two's_complement). - Floating-point arrays (`Float32Array` and `Float64Array`) store the number using [IEEE 754](https://en.wikipedia.org/wiki/IEEE_754) floating-point format. The [`Number`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_encoding) reference has more information about the exact format. JavaScript numbers use double precision floating point format by default, which is the same as `Float64Array`. `Float32Array` uses 23 (instead of 52) bits for the mantissa and 8 (instead of 11) bits for the exponent. Note that the spec requires all {{jsxref("NaN")}} values to use the same bit encoding, but the exact bit pattern is implementation-dependent. - `Uint8ClampedArray` is a special case. It stores the number in binary like `Uint8Array` does, but when you store a number outside the range, it _clamps_ the number to the range 0 to 255 by mathematical value, instead of truncating the most significant bits. All typed arrays except `Int8Array`, `Uint8Array`, and `Uint8ClampedArray` store each element using multiple bytes. These bytes can either be ordered from most significant to least significant (big-endian) or from least significant to most significant (little-endian). See [Endianness](/en-US/docs/Glossary/Endianness) for more explanation. Typed arrays always use the platform's native byte order. If you want to specify the endianness when writing and reading from buffers, you should use a {{jsxref("DataView")}} instead. When writing to these typed arrays, values that are outside the representable range are normalized. - All integer arrays (except `Uint8ClampedArray`) use [fixed-width number conversion](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#fixed-width_number_conversion), which first truncates the decimal part of the number and then takes the lowest bits. - `Uint8ClampedArray` first clamps the number to the range 0 to 255 (values greater than 255 become 255 and values less than 0 become 0). It then _rounds_ (instead of flooring) the result to the nearest integer, with half-to-even; meaning if the number is exactly between two integers, it rounds to the nearest even integer. For example, `0.5` becomes `0`, `1.5` becomes `2`, and `2.5` becomes `2`. - `Float32Array` performs a "round to even" to convert 64-bit floating point numbers to 32-bit. This is the same algorithm as provided by {{jsxref("Math.fround()")}}. ### Behavior when viewing a resizable buffer When a `TypedArray` is created as a view of a [resizable buffer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer#resizing_arraybuffers), resizing the underlying buffer will have different effects on the size of the `TypedArray` depending on whether the `TypedArray` is constructed as length-tracking. If a typed array is created without a specific size by omitting the third parameter or passing `undefined`, the typed array will become _length-tracking_, and will automatically resize to fit the underlying `buffer` as the latter is resized: ```js const buffer = new ArrayBuffer(8, { maxByteLength: 16 }); const float32 = new Float32Array(buffer); console.log(float32.byteLength); // 8 console.log(float32.length); // 2 buffer.resize(12); console.log(float32.byteLength); // 12 console.log(float32.length); // 3 ``` If a typed array is created with a specific size using the third `length` parameter, it won't resize to contain the `buffer` as the latter is grown: ```js const buffer = new ArrayBuffer(8, { maxByteLength: 16 }); const float32 = new Float32Array(buffer, 0, 2); console.log(float32.byteLength); // 8 console.log(float32.length); // 2 console.log(float32[0]); // 0, the initial value buffer.resize(12); console.log(float32.byteLength); // 8 console.log(float32.length); // 2 console.log(float32[0]); // 0, the initial value ``` When a `buffer` is shrunk, the viewing typed array may become out of bounds, in which case the typed array's observed size will decrease to 0. This is the only case where a non-length-tracking typed array's length may change. ```js const buffer = new ArrayBuffer(8, { maxByteLength: 16 }); const float32 = new Float32Array(buffer, 0, 2); buffer.resize(7); console.log(float32.byteLength); // 0 console.log(float32.length); // 0 console.log(float32[0]); // undefined ``` If you then grow the `buffer` again to bring the typed array back in bounds, the typed array's size will be restored to its original value. ```js buffer.resize(8); console.log(float32.byteLength); // 8 console.log(float32.length); // 2 console.log(float32[0]); // 0 - back in bounds again! ``` The same can happen for length-tracking typed arrays as well, if the buffer is shrunk beyond the `byteOffset`. ```js const buffer = new ArrayBuffer(8, { maxByteLength: 16 }); const float32 = new Float32Array(buffer, 4); // float32 is length-tracking, but it only extends from the 4th byte // to the end of the buffer, so if the buffer is resized to be shorter // than 4 bytes, the typed array will become out of bounds buffer.resize(3); console.log(float32.byteLength); // 0 ``` ## Constructor This object cannot be instantiated directly β€” attempting to construct it with `new` throws a {{jsxref("TypeError")}}. ```js new (Object.getPrototypeOf(Int8Array))(); // TypeError: Abstract class TypedArray not directly constructable ``` Instead, you create an instance of a typed array of a particular type, such as an {{jsxref("Int8Array")}} or a {{jsxref("BigInt64Array")}}. These objects all have a common syntax for their constructors: ```js-nolint new TypedArray() new TypedArray(length) new TypedArray(typedArray) new TypedArray(object) new TypedArray(buffer) new TypedArray(buffer, byteOffset) new TypedArray(buffer, byteOffset, length) ``` Where `TypedArray` is a constructor for one of the concrete types. > **Note:** All `TypedArray` subclasses' constructors can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call one without `new` throws a {{jsxref("TypeError")}}. ### Parameters - `typedArray` - : When called with an instance of a `TypedArray` subclass, the `typedArray` gets copied into a new typed array. For a non-[bigint](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) `TypedArray` constructor, the `typedArray` parameter can only be of one of the non-[bigint](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) types (such as {{jsxref("Int32Array")}}). Similarly, for a [bigint](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) `TypedArray` constructor ({{jsxref("BigInt64Array")}} or {{jsxref("BigUint64Array")}}), the `typedArray` parameter can only be of one of the [bigint](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) types. Each value in `typedArray` is converted to the corresponding type of the constructor before being copied into the new array. The length of the new typed array will be same as the length of the `typedArray` argument. - `object` - : When called with an object that's not a `TypedArray` instance, a new typed array is created in the same way as the [`TypedArray.from()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from) method. - `length` {{optional_inline}} - : When called with a non-object, the parameter will be treated as a number specifying the length of the typed array. An internal array buffer is created in memory, of size `length` multiplied by [`BYTES_PER_ELEMENT`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/BYTES_PER_ELEMENT) bytes, filled with zeros. Omitting all parameters is equivalent to using `0` as `length`. - `buffer`, `byteOffset` {{optional_inline}}, `length` {{optional_inline}} - : When called with an [`ArrayBuffer`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or [`SharedArrayBuffer`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance, and optionally a `byteOffset` and a `length` argument, a new typed array view is created that views the specified buffer. The `byteOffset` (in bytes) and `length` (in number of elements, each occupying [`BYTES_PER_ELEMENT`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/BYTES_PER_ELEMENT) bytes) parameters specify the memory range that will be exposed by the typed array view. If both are omitted, all of `buffer` is viewed; if only `length` is omitted, the remainder of `buffer` starting from `byteOffset` is viewed. If `length` is omitted, the typed array becomes [length-tracking](#behavior_when_viewing_a_resizable_buffer). ### Exceptions All `TypeArray` subclass constructors operate in the same way. They would all throw the following exceptions: - {{jsxref("TypeError")}} - : Thrown in one of the following cases: - A `typedArray` is passed but it is a [bigint](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) type while the current constructor is not, or vice versa. - A `typedArray` is passed but the buffer it's viewing is detached, or a detached `buffer` is directly passed. - {{jsxref("RangeError")}} - : Thrown in one of the following cases: - The new typed array's length is too large. - The length of `buffer` (if the `length` parameter is not specified) or `byteOffset` is not an integral multiple of the new typed array's element size. - `byteOffset` is not a valid array index (an integer between 0 and 2<sup>53</sup> - 1). - When creating a view from a buffer, the bounds are outside the buffer. In other words, `byteOffset + length * TypedArray.BYTES_PER_ELEMENT > buffer.byteLength`. ## Static properties These properties are defined on the `TypedArray` constructor object and are thus shared by all `TypedArray` subclass constructors. - {{jsxref("TypedArray/@@species", "TypedArray[@@species]")}} - : The constructor function used to create derived objects. All `TypedArray` subclasses also have the following static properties: - {{jsxref("TypedArray.BYTES_PER_ELEMENT")}} - : Returns a number value of the element size for the different `TypedArray` objects. ## Static methods These methods are defined on the `TypedArray` constructor object and are thus shared by all `TypedArray` subclass constructors. - {{jsxref("TypedArray.from()")}} - : Creates a new `TypedArray` from an array-like or iterable object. See also {{jsxref("Array.from()")}}. - {{jsxref("TypedArray.of()")}} - : Creates a new `TypedArray` with a variable number of arguments. See also {{jsxref("Array.of()")}}. ## Instance properties These properties are defined on `TypedArray.prototype` and shared by all `TypedArray` subclass instances. - {{jsxref("TypedArray.prototype.buffer")}} - : Returns the {{jsxref("ArrayBuffer")}} referenced by the typed array. - {{jsxref("TypedArray.prototype.byteLength")}} - : Returns the length (in bytes) of the typed array. - {{jsxref("TypedArray.prototype.byteOffset")}} - : Returns the offset (in bytes) of the typed array from the start of its {{jsxref("ArrayBuffer")}}. - {{jsxref("Object/constructor", "TypedArray.prototype.constructor")}} - : The constructor function that created the instance object. `TypedArray.prototype.constructor` is the hidden `TypedArray` constructor function, but each typed array subclass also defines its own `constructor` property. - {{jsxref("TypedArray.prototype.length")}} - : Returns the number of elements held in the typed array. - `TypedArray.prototype[@@toStringTag]` - : The initial value of the [`TypedArray.prototype[@@toStringTag]`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is a getter that returns the same string as the typed array constructor's name. It returns `undefined` if the `this` value is not one of the typed array subclasses. This property is used in {{jsxref("Object.prototype.toString()")}}. However, because `TypedArray` also has its own [`toString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/toString) method, this property is not used unless you call [`Object.prototype.toString.call()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) with a typed array as `thisArg`. All `TypedArray` subclasses also have the following instance properties: - {{jsxref("TypedArray.prototype.BYTES_PER_ELEMENT")}} - : Returns a number value of the element size for the different `TypedArray` objects. ## Instance methods These methods are defined on the `TypedArray` prototype object and are thus shared by all `TypedArray` subclass instances. - {{jsxref("TypedArray.prototype.at()")}} - : Takes an integer value and returns the item at that index. This method allows for negative integers, which count back from the last item. - {{jsxref("TypedArray.prototype.copyWithin()")}} - : Copies a sequence of array elements within the array. See also {{jsxref("Array.prototype.copyWithin()")}}. - {{jsxref("TypedArray.prototype.entries()")}} - : Returns a new _array iterator_ object that contains the key/value pairs for each index in the array. See also {{jsxref("Array.prototype.entries()")}}. - {{jsxref("TypedArray.prototype.every()")}} - : Tests whether all elements in the array pass the test provided by a function. See also {{jsxref("Array.prototype.every()")}}. - {{jsxref("TypedArray.prototype.fill()")}} - : Fills all the elements of an array from a start index to an end index with a static value. See also {{jsxref("Array.prototype.fill()")}}. - {{jsxref("TypedArray.prototype.filter()")}} - : Creates a new array with all of the elements of this array for which the provided filtering function returns `true`. See also {{jsxref("Array.prototype.filter()")}}. - {{jsxref("TypedArray.prototype.find()")}} - : Returns the first `element` in the array that satisfies a provided testing function, or `undefined` if no appropriate element is found. See also {{jsxref("Array.prototype.find()")}}. - {{jsxref("TypedArray.prototype.findIndex()")}} - : Returns the first index value in the array that has an element that satisfies a provided testing function, or `-1` if no appropriate element was found. See also {{jsxref("Array.prototype.findIndex()")}}. - {{jsxref("TypedArray.prototype.findLast()")}} - : Returns the value of the last element in the array that satisfies a provided testing function, or `undefined` if no appropriate element is found. See also {{jsxref("Array.prototype.findLast()")}}. - {{jsxref("TypedArray.prototype.findLastIndex()")}} - : Returns the index of the last element in the array that satisfies a provided testing function, or `-1` if no appropriate element was found. See also {{jsxref("Array.prototype.findLastIndex()")}}. - {{jsxref("TypedArray.prototype.forEach()")}} - : Calls a function for each element in the array. See also {{jsxref("Array.prototype.forEach()")}}. - {{jsxref("TypedArray.prototype.includes()")}} - : Determines whether a typed array includes a certain element, returning `true` or `false` as appropriate. See also {{jsxref("Array.prototype.includes()")}}. - {{jsxref("TypedArray.prototype.indexOf()")}} - : Returns the first (least) index of an element within the array equal to the specified value, or `-1` if none is found. See also {{jsxref("Array.prototype.indexOf()")}}. - {{jsxref("TypedArray.prototype.join()")}} - : Joins all elements of an array into a string. See also {{jsxref("Array.prototype.join()")}}. - {{jsxref("TypedArray.prototype.keys()")}} - : Returns a new array iterator that contains the keys for each index in the array. See also {{jsxref("Array.prototype.keys()")}}. - {{jsxref("TypedArray.prototype.lastIndexOf()")}} - : Returns the last (greatest) index of an element within the array equal to the specified value, or `-1` if none is found. See also {{jsxref("Array.prototype.lastIndexOf()")}}. - {{jsxref("TypedArray.prototype.map()")}} - : Creates a new array with the results of calling a provided function on every element in this array. See also {{jsxref("Array.prototype.map()")}}. - {{jsxref("TypedArray.prototype.reduce()")}} - : Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value. See also {{jsxref("Array.prototype.reduce()")}}. - {{jsxref("TypedArray.prototype.reduceRight()")}} - : Apply a function against an accumulator and each value of the array (from right-to-left) as to reduce it to a single value. See also {{jsxref("Array.prototype.reduceRight()")}}. - {{jsxref("TypedArray.prototype.reverse()")}} - : Reverses the order of the elements of an array β€” the first becomes the last, and the last becomes the first. See also {{jsxref("Array.prototype.reverse()")}}. - {{jsxref("TypedArray.prototype.set()")}} - : Stores multiple values in the typed array, reading input values from a specified array. - {{jsxref("TypedArray.prototype.slice()")}} - : Extracts a section of an array and returns a new array. See also {{jsxref("Array.prototype.slice()")}}. - {{jsxref("TypedArray.prototype.some()")}} - : Returns `true` if at least one element in this array satisfies the provided testing function. See also {{jsxref("Array.prototype.some()")}}. - {{jsxref("TypedArray.prototype.sort()")}} - : Sorts the elements of an array in place and returns the array. See also {{jsxref("Array.prototype.sort()")}}. - {{jsxref("TypedArray.prototype.subarray()")}} - : Returns a new `TypedArray` from the given start and end element index. - {{jsxref("TypedArray.prototype.toLocaleString()")}} - : Returns a localized string representing the array and its elements. See also {{jsxref("Array.prototype.toLocaleString()")}}. - {{jsxref("TypedArray.prototype.toReversed()")}} - : Returns a new array with the elements in reversed order, without modifying the original array. - {{jsxref("TypedArray.prototype.toSorted()")}} - : Returns a new array with the elements sorted in ascending order, without modifying the original array. - {{jsxref("TypedArray.prototype.toString()")}} - : Returns a string representing the array and its elements. See also {{jsxref("Array.prototype.toString()")}}. - {{jsxref("TypedArray.prototype.values()")}} - : Returns a new _array iterator_ object that contains the values for each index in the array. See also {{jsxref("Array.prototype.values()")}}. - {{jsxref("TypedArray.prototype.with()")}} - : Returns a new array with the element at the given index replaced with the given value, without modifying the original array. - [`TypedArray.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/@@iterator) - : Returns a new _array iterator_ object that contains the values for each index in the array. ## Examples ### Property access You can reference elements in the array using standard array index syntax (that is, using bracket notation). However, getting or setting indexed properties on typed arrays will not search in the prototype chain for this property, even when the indices are out of bound. Indexed properties will consult the {{jsxref("ArrayBuffer")}} and will never look at object properties. You can still use named properties, just like with all objects. ```js // Setting and getting using standard array syntax const int16 = new Int16Array(2); int16[0] = 42; console.log(int16[0]); // 42 // Indexed properties on prototypes are not consulted (Fx 25) Int8Array.prototype[20] = "foo"; new Int8Array(32)[20]; // 0 // even when out of bound Int8Array.prototype[20] = "foo"; new Int8Array(8)[20]; // undefined // or with negative integers Int8Array.prototype[-1] = "foo"; new Int8Array(8)[-1]; // undefined // Named properties are allowed, though (Fx 30) Int8Array.prototype.foo = "bar"; new Int8Array(32).foo; // "bar" ``` ### Cannot be frozen `TypedArray`s that aren't empty cannot be frozen, as their underlying `ArrayBuffer` could be mutated through another `TypedArray` view of the buffer. This would mean that the object would never genuinely be frozen. ```js example-bad const i8 = Int8Array.of(1, 2, 3); Object.freeze(i8); // TypeError: Cannot freeze array buffer views with elements ``` ### ByteOffset must be aligned When constructing a `TypedArray` as a view onto an `ArrayBuffer`, the `byteOffset` argument must be aligned to its element size; in other words, the offset must be a multiple of `BYTES_PER_ELEMENT`. ```js example-bad const i32 = new Int32Array(new ArrayBuffer(4), 1); // RangeError: start offset of Int32Array should be a multiple of 4 ``` ```js example-good const i32 = new Int32Array(new ArrayBuffer(4), 0); ``` ### ByteLength must be aligned Like the `byteOffset` parameter, the `byteLength` property of an `ArrayBuffer` passed to a `TypedArray`'s constructor must be a multiple of the constructor's `BYTES_PER_ELEMENT`. ```js example-bad const i32 = new Int32Array(new ArrayBuffer(3)); // RangeError: byte length of Int32Array should be a multiple of 4 ``` ```js example-good const i32 = new Int32Array(new ArrayBuffer(4)); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of typed arrays 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("ArrayBuffer")}} - {{jsxref("DataView")}} - {{domxref("TextDecoder")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/at/index.md
--- title: TypedArray.prototype.at() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/at page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.at --- {{JSRef}} The **`at()`** method of {{jsxref("TypedArray")}} instances takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the typed array. This method has the same algorithm as {{jsxref("Array.prototype.at()")}}. {{EmbedInteractiveExample("pages/js/typedarray-at.html")}} ## Syntax ```js-nolint at(index) ``` ### Parameters - `index` - : Zero-based index of the typed array element to be returned, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). Negative index counts back from the end of the typed array β€” if `index < 0`, `index + array.length` is accessed. ### Return value The element in the typed array matching the given index. Always returns {{jsxref("undefined")}} if `index < -array.length` or `index >= array.length` without attempting to access the corresponding property. ## Description See {{jsxref("Array.prototype.at()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Return the last value of a typed array The following example provides a function which returns the last element found in a specified array. ```js const uint8 = new Uint8Array([1, 2, 4, 7, 11, 18]); // A function which returns the last item of a given array function returnLast(arr) { return arr.at(-1); } const lastItem = returnLast(uint8); console.log(lastItem); // 18 ``` ### Comparing methods Here we compare different ways to select the penultimate (last but one) item of a {{jsxref("TypedArray")}}. Whilst all below methods are valid, it highlights the succinctness and readability of the `at()` method. ```js // Our typed array with values const uint8 = new Uint8Array([1, 2, 4, 7, 11, 18]); // Using length property const lengthWay = uint8[uint8.length - 2]; console.log(lengthWay); // 11 // Using slice() method. Note an array is returned const sliceWay = uint8.slice(-2, -1); console.log(sliceWay[0]); // 11 // Using at() method const atWay = uint8.at(-2); console.log(atWay); // 11 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.at` in `core-js`](https://github.com/zloirock/core-js#relative-indexing-method) - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("TypedArray")}} - {{jsxref("TypedArray.prototype.findIndex()")}} - {{jsxref("TypedArray.prototype.indexOf()")}} - {{jsxref("TypedArray.prototype.with()")}} - {{jsxref("Array.prototype.at()")}} - {{jsxref("String.prototype.at()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/reduceright/index.md
--- title: TypedArray.prototype.reduceRight() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/reduceRight page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.reduceRight --- {{JSRef}} The **`reduceRight()`** method of {{jsxref("TypedArray")}} instances applies a function against an accumulator and each value of the typed array (from right-to-left) to reduce it to a single value. This method has the same algorithm as {{jsxref("Array.prototype.reduceRight()")}}. {{EmbedInteractiveExample("pages/js/typedarray-reduceright.html")}} ## Syntax ```js-nolint reduceRight(callbackFn) reduceRight(callbackFn, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the typed array. 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 `reduceRight()`. 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 last element of the typed array. - `currentValue` - : The value of the current element. On the first call, its value is the last element if `initialValue` is specified; otherwise its value is the second-to-last element. - `currentIndex` - : The index position of `currentValue` in the typed array. On the first call, its value is `array.length - 1` if `initialValue` is specified, otherwise `array.length - 2`. - `array` - : The typed array `reduceRight()` was called upon. - `initialValue` {{optional_inline}} - : Value to use as accumulator to the first call of the `callbackFn`. If no initial value is supplied, the last element in the typed array will be used and skipped. Calling `reduceRight()` on an empty typed array without an initial value creates a `TypeError`. ### Return value The value that results from the reduction. ## Description See {{jsxref("Array.prototype.reduceRight()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Sum up all values within an array ```js const total = new Uint8Array([0, 1, 2, 3]).reduceRight((a, b) => a + b); // total === 6 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.reduceRight` 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("TypedArray.prototype.map()")}} - {{jsxref("TypedArray.prototype.reduce()")}} - {{jsxref("Array.prototype.reduceRight()")}} - {{jsxref("Object.groupBy()")}} - {{jsxref("Map.groupBy()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/map/index.md
--- title: TypedArray.prototype.map() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/map page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.map --- {{JSRef}} The **`map()`** method of {{jsxref("TypedArray")}} instances creates a new typed array populated with the results of calling a provided function on every element in the calling typed array. This method has the same algorithm as {{jsxref("Array.prototype.map()")}}. {{EmbedInteractiveExample("pages/js/typedarray-map.html", "shorter")}} ## Syntax ```js-nolint map(callbackFn) map(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the typed array. Its return value is added as a single element in the new typed array. The function is called with the following arguments: - `element` - : The current element being processed in the typed array. - `index` - : The index of the current element being processed in the typed array. - `array` - : The typed array `map()` was called upon. - `thisArg` {{optional_inline}} - : A value to use as `this` when executing `callbackFn`. See [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). ### Return value A new typed array with each element being the result of the callback function. ## Description See {{jsxref("Array.prototype.map()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Mapping a typed array to a typed array of square roots The following code takes a typed array and creates a new typed array containing the square roots of the numbers in the first typed array. ```js const numbers = new Uint8Array([1, 4, 9]); const roots = numbers.map(Math.sqrt); // roots is now: Uint8Array [1, 2, 3], // numbers is still Uint8Array [1, 4, 9] ``` ### Mapping a typed array of numbers using a function containing an argument The following code shows how `map()` works when a function requiring one argument is used with it. The argument will automatically be assigned to each element of the typed array as `map()` loops through the original typed array. ```js const numbers = new Uint8Array([1, 4, 9]); const doubles = numbers.map((num) => num * 2); // doubles is now Uint8Array [2, 8, 18] // numbers is still Uint8Array [1, 4, 9] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.map` 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("TypedArray.prototype.forEach()")}} - {{jsxref("TypedArray.from()")}} - {{jsxref("Array.prototype.map()")}} - {{jsxref("Map")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/from/index.md
--- title: TypedArray.from() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/from page-type: javascript-static-method browser-compat: javascript.builtins.TypedArray.from --- {{JSRef}} The **`TypedArray.from()`** static method creates a new [typed array](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#typedarray_objects) from an array-like or iterable object. This method is nearly the same as {{jsxref("Array.from()")}}. {{EmbedInteractiveExample("pages/js/typedarray-from.html", "shorter")}} ## Syntax ```js-nolint TypedArray.from(arrayLike, mapFn) TypedArray.from(arrayLike, mapFn, thisArg) ``` Where `TypedArray` is one of: - {{jsxref("Int8Array")}} - {{jsxref("Uint8Array")}} - {{jsxref("Uint8ClampedArray")}} - {{jsxref("Int16Array")}} - {{jsxref("Uint16Array")}} - {{jsxref("Int32Array")}} - {{jsxref("Uint32Array")}} - {{jsxref("Float32Array")}} - {{jsxref("Float64Array")}} - {{jsxref("BigInt64Array")}} - {{jsxref("BigUint64Array")}} ### Parameters - `arrayLike` - : An iterable or array-like object to convert to a typed array. - `mapFn` {{optional_inline}} - : A function to call on every element of the typed array. If provided, every value to be added to the array is first passed through this function, and `mapFn`'s return value is added to the typed array instead. The function is called with the following arguments: - `element` - : The current element being processed in the typed array. - `index` - : The index of the current element being processed in the typed array. - `thisArg` {{optional_inline}} - : Value to use as `this` when executing `mapFn`. ### Return value A new {{jsxref("TypedArray")}} instance. ## Description See {{jsxref("Array.from()")}} for more details. There are some subtle distinctions between {{jsxref("Array.from()")}} and `TypedArray.from()` (note: the `this` value mentioned below is the `this` value that `TypedArray.from()` was called with, not the `thisArg` argument used to invoke `mapFn`): - If the `this` value of `TypedArray.from()` is not a constructor, `TypedArray.from()` will throw a {{jsxref("TypeError")}}, while `Array.from()` defaults to creating a new {{jsxref("Array")}}. - The object constructed by `this` must be a `TypedArray` instance, while `Array.from()` allows its `this` value to be constructed to any object. - When the `source` parameter is an iterator, `TypedArray.from()` first collects all the values from the iterator, then creates an instance of `this` using the count, and finally sets the values on the instance. `Array.from()` sets each value as it receives them from the iterator, then sets its `length` at the end. - `TypedArray.from()` uses `[[Set]]` while `Array.from()` uses `[[DefineOwnProperty]]`. Hence, when working with {{jsxref("Proxy")}} objects, it calls [`handler.set()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/set) to create new elements rather than [`handler.defineProperty()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/defineProperty). - When `Array.from()` gets an array-like which isn't an iterator, it respects holes. `TypedArray.from()` will ensure the result is dense. ## Examples ### From an iterable object (Set) ```js const s = new Set([1, 2, 3]); Uint8Array.from(s); // Uint8Array [ 1, 2, 3 ] ``` ### From a string ```js Int16Array.from("123"); // Int16Array [ 1, 2, 3 ] ``` ### Use with arrow function and map Using an arrow function as the map function to manipulate the elements ```js Float32Array.from([1, 2, 3], (x) => x + x); // Float32Array [ 2, 4, 6 ] ``` ### Generate a sequence of numbers ```js Uint8Array.from({ length: 5 }, (v, k) => k); // Uint8Array [ 0, 1, 2, 3, 4 ] ``` ### Calling from() on non-TypedArray constructors The `this` value of `from()` must be a constructor that returns a `TypedArray` instance. ```js function NotArray(len) { console.log("NotArray called with length", len); } Int8Array.from.call({}, []); // TypeError: #<Object> is not a constructor Int8Array.from.call(NotArray, []); // NotArray called with length 0 // TypeError: Method %TypedArray%.from called on incompatible receiver #<NotArray> ``` ```js function NotArray2(len) { console.log("NotArray2 called with length", len); return new Uint8Array(len); } console.log(Int8Array.from.call(NotArray2, [1, 2, 3])); // NotArray2 called with length 3 // Uint8Array(3) [ 1, 2, 3 ] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.from` 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("TypedArray.of()")}} - {{jsxref("TypedArray.prototype.map()")}} - {{jsxref("Array.from()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/reverse/index.md
--- title: TypedArray.prototype.reverse() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/reverse page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.reverse --- {{JSRef}} The **`reverse()`** method of {{jsxref("TypedArray")}} instances reverses a typed array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same typed array, the first typed array element now becoming the last, and the last typed array element becoming the first. In other words, elements order in the typed array will be turned towards the direction opposite to that previously stated. This method has the same algorithm as {{jsxref("Array.prototype.reverse()")}}. {{EmbedInteractiveExample("pages/js/typedarray-reverse.html", "shorter")}} ## Syntax ```js-nolint reverse() ``` ### Parameters None. ### Return value The reference to the original typed array, now reversed. Note that the typed array is reversed _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description See {{jsxref("Array.prototype.reverse()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Using reverse() ```js const uint8 = new Uint8Array([1, 2, 3]); uint8.reverse(); console.log(uint8); // Uint8Array [3, 2, 1] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.reverse` 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("TypedArray.prototype.join()")}} - {{jsxref("TypedArray.prototype.sort()")}} - {{jsxref("TypedArray.prototype.toReversed()")}} - {{jsxref("Array.prototype.reverse()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/copywithin/index.md
--- title: TypedArray.prototype.copyWithin() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/copyWithin page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.copyWithin --- {{JSRef}} The **`copyWithin()`** method of {{jsxref("TypedArray")}} instances shallow copies part of this typed array to another location in the same typed array and returns this typed array without modifying its length. This method has the same algorithm as {{jsxref("Array.prototype.copyWithin()")}}. {{EmbedInteractiveExample("pages/js/typedarray-copywithin.html")}} ## Syntax ```js-nolint copyWithin(target, start) copyWithin(target, start, end) ``` ### Parameters - `target` - : Zero-based index at which to copy the sequence to, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). This corresponds to where the element at `start` will be copied to, and all elements between `start` and `end` are copied to succeeding indices. - `start` - : Zero-based index at which to start copying elements from, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). - `end` {{optional_inline}} - : Zero-based index at which to end copying elements from, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). `copyWithin()` copies up to but not including `end`. ### Return value The modified typed array. ## Description See {{jsxref("Array.prototype.copyWithin()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Using copyWithin() ```js const buffer = new ArrayBuffer(8); const uint8 = new Uint8Array(buffer); uint8.set([1, 2, 3]); console.log(uint8); // Uint8Array [ 1, 2, 3, 0, 0, 0, 0, 0 ] uint8.copyWithin(3, 0, 3); console.log(uint8); // Uint8Array [ 1, 2, 3, 1, 2, 3, 0, 0 ] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.copyWithin` 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("Array.prototype.copyWithin()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/tostring/index.md
--- title: TypedArray.prototype.toString() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/toString page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.toString --- {{JSRef}} The **`toString()`** method of {{jsxref("TypedArray")}} instances returns a string representing the specified typed array and its elements. This method has the same algorithm as {{jsxref("Array.prototype.toString()")}}. {{EmbedInteractiveExample("pages/js/typedarray-tostring.html", "shorter")}} ## Syntax ```js-nolint toString() ``` ### Parameters None. ### Return value A string representing the elements of the typed array. ## Description See {{jsxref("Array.prototype.toString()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Converting a typed array to a string ```js const uint8 = new Uint8Array([1, 2, 3]); // Explicit conversion console.log(uint8.toString()); // 1,2,3 // Implicit conversion console.log(`${uint8}`); // 1,2,3 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("TypedArray")}} - {{jsxref("TypedArray.prototype.join()")}} - {{jsxref("TypedArray.prototype.toLocaleString()")}} - {{jsxref("Array.prototype.toString()")}} - {{jsxref("String.prototype.toString()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/byteoffset/index.md
--- title: TypedArray.prototype.byteOffset slug: Web/JavaScript/Reference/Global_Objects/TypedArray/byteOffset page-type: javascript-instance-accessor-property browser-compat: javascript.builtins.TypedArray.byteOffset --- {{JSRef}} The **`byteOffset`** accessor property of {{jsxref("TypedArray")}} instances returns the offset (in bytes) of this typed array from the start of its {{jsxref("ArrayBuffer")}} or {{jsxref("SharedArrayBuffer")}}. ## Description The `byteOffset` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when a _TypedArray_ is constructed and cannot be changed. _TypedArray_ is one of the [TypedArray objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#typedarray_objects). ## Examples ### Using the byteOffset property ```js const buffer = new ArrayBuffer(8); const uint8array1 = new Uint8Array(buffer); uint8array1.byteOffset; // 0 (no offset specified) const uint8array2 = new Uint8Array(buffer, 3); uint8array2.byteOffset; // 3 (as specified when constructing Uint8Array) ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("TypedArray")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/buffer/index.md
--- title: TypedArray.prototype.buffer slug: Web/JavaScript/Reference/Global_Objects/TypedArray/buffer page-type: javascript-instance-accessor-property browser-compat: javascript.builtins.TypedArray.buffer --- {{JSRef}} The **`buffer`** accessor property of {{jsxref("TypedArray")}} instances returns the {{jsxref("ArrayBuffer")}} or {{jsxref("SharedArrayBuffer")}} referenced by this typed array at construction time. {{EmbedInteractiveExample("pages/js/typedarray-buffer.html", "shorter")}} ## Description The `buffer` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the _TypedArray_ is constructed and cannot be changed. _TypedArray_ is one of the [TypedArray objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#typedarray_objects). Because a typed array is a _view_ of a buffer, the underlying buffer may be longer than the typed array itself. ## Examples ### Using the buffer property ```js const buffer = new ArrayBuffer(8); const uint16 = new Uint16Array(buffer); uint16.buffer; // ArrayBuffer { byteLength: 8 } ``` ### Accessing the underlying buffer from a sliced array view ```js const buffer = new ArrayBuffer(1024); const arr = new Uint8Array(buffer, 64, 128); console.log(arr.byteLength); // 128 console.log(arr.buffer.byteLength); // 1024 console.log(arr.buffer === buffer); // true ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("TypedArray")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/slice/index.md
--- title: TypedArray.prototype.slice() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/slice page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.slice --- {{JSRef}} The **`slice()`** method of {{jsxref("TypedArray")}} instances returns a copy of a portion of a typed array into a new typed array object selected from `start` to `end` (`end` not included) where `start` and `end` represent the index of items in that typed array. The original typed array will not be modified. This method has the same algorithm as {{jsxref("Array.prototype.slice()")}}. {{EmbedInteractiveExample("pages/js/typedarray-slice.html", "shorter")}} ## 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). - `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`. ### Return value A new typed array containing the extracted elements. ## Description See {{jsxref("Array.prototype.slice()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Return a portion of an existing typed array ```js const uint8 = new Uint8Array([1, 2, 3]); uint8.slice(1); // Uint8Array [ 2, 3 ] uint8.slice(2); // Uint8Array [ 3 ] uint8.slice(-2); // Uint8Array [ 2, 3 ] uint8.slice(0, 1); // Uint8Array [ 1 ] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.slice` 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("Array.prototype.slice()")}} - {{jsxref("String.prototype.slice()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/subarray/index.md
--- title: TypedArray.prototype.subarray() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/subarray page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.subarray --- {{JSRef}} The **`subarray()`** method of {{jsxref("TypedArray")}} instances returns a new typed array on the same {{jsxref("ArrayBuffer")}} store and with the same element types as for this typed array. The begin offset is **inclusive** and the end offset is **exclusive**. {{EmbedInteractiveExample("pages/js/typedarray-subarray.html")}} ## Syntax ```js-nolint subarray() subarray(begin) subarray(begin, end) ``` ### Parameters - `begin` {{optional_inline}} - : Element to begin at. The offset is inclusive. The whole array will be included in the new view if this value is not specified. - `end` {{optional_inline}} - : Element to end at. The offset is exclusive. If not specified, all elements from the one specified by `begin` to the end of the array are included in the new view. ### Return value A new {{jsxref("TypedArray")}} object. ## Description The range specified by `begin` and `end` is clamped to the valid index range for the current array; if the computed length of the new array would be negative, it's clamped to zero. If either `begin` or `end` is negative, it refers to an index from the end of the array instead of from the beginning. Also note that this is creating a new view on the existing buffer; changes to the new object's contents will impact the original object and vice versa. ## Examples ### Using the subarray() method ```js const buffer = new ArrayBuffer(8); const uint8 = new Uint8Array(buffer); uint8.set([1, 2, 3]); console.log(uint8); // Uint8Array [ 1, 2, 3, 0, 0, 0, 0, 0 ] const sub = uint8.subarray(0, 4); console.log(sub); // Uint8Array [ 1, 2, 3, 0 ] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.subarray` 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")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/findlast/index.md
--- title: TypedArray.prototype.findLast() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/findLast page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.findLast --- {{JSRef}} The **`findLast()`** method of {{jsxref("TypedArray")}} instances iterates the typed array in reverse order and returns the value of the first element that satisfies the provided testing function. If no elements satisfy the testing function, {{jsxref("undefined")}} is returned. This method has the same algorithm as {{jsxref("Array.prototype.findLast()")}}. {{EmbedInteractiveExample("pages/js/typedarray-findlast.html")}} ## Syntax ```js-nolint findLast(callbackFn) findLast(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the typed array. 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 in the typed array. - `index` - : The index of the current element being processed in the typed array. - `array` - : The typed array `findLast()` was called upon. - `thisArg` {{optional_inline}} - : A value to use as `this` when executing `callbackFn`. See [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). ### Return value The last (highest-index) element in the typed array that satisfies the provided testing function; {{jsxref("undefined")}} if no matching element is found. ## Description See {{jsxref("Array.prototype.findLast()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Find the last prime number in a typed array The following example returns the value of the last element in the typed array that is a prime number, or {{jsxref("undefined")}} if there is no prime number. ```js function isPrime(element) { if (element % 2 === 0 || element < 2) { return false; } for (let factor = 3; factor <= Math.sqrt(element); factor += 2) { if (element % factor === 0) { return false; } } return true; } let uint8 = new Uint8Array([4, 6, 8, 12]); console.log(uint8.findLast(isPrime)); // undefined (no primes in array) uint8 = new Uint8Array([4, 5, 7, 8, 9, 11, 12]); console.log(uint8.findLast(isPrime)); // 11 ``` ### All elements are visited and may be modified by the callback The following examples show that all elements _are_ visited, and that the value passed to the callback is their value when visited: ```js // Declare array with no elements at indexes 2, 3, and 4 // The missing elements will be initialized to zero. const uint8 = new Uint8Array([0, 1, , , , 5, 6]); // Iterate through the elements in reverse order. // Note that all elements are visited. uint8.findLast((value, index) => { console.log(`Visited index ${index} with value ${value}`); }); // Shows all indexes, including deleted uint8.findLast((value, index) => { // Modify element 3 on first iteration if (index === 6) { console.log("Set uint8[3] to 44"); uint8[3] = 44; } // Element 3 is still visited but will have a new value. console.log(`Visited index ${index} with value ${value}`); }); // Visited index 6 with value 6 // Visited index 5 with value 5 // Visited index 4 with value 0 // Visited index 3 with value 0 // Visited index 2 with value 0 // Visited index 1 with value 1 // Visited index 0 with value 0 // Set uint8[3] to 44 // Visited index 6 with value 6 // Visited index 5 with value 5 // Visited index 4 with value 0 // Visited index 3 with value 44 // Visited index 2 with value 0 // Visited index 1 with value 1 // Visited index 0 with value 0 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.findLast` in `core-js`](https://github.com/zloirock/core-js#array-find-from-last) - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("TypedArray")}} - {{jsxref("TypedArray.prototype.find()")}} - {{jsxref("TypedArray.prototype.findIndex()")}} - {{jsxref("TypedArray.prototype.findLastIndex()")}} - {{jsxref("TypedArray.prototype.includes()")}} - {{jsxref("TypedArray.prototype.filter()")}} - {{jsxref("TypedArray.prototype.every()")}} - {{jsxref("TypedArray.prototype.some()")}} - {{jsxref("Array.prototype.findLast()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/includes/index.md
--- title: TypedArray.prototype.includes() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/includes page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.includes --- {{JSRef}} The **`includes()`** method of {{jsxref("TypedArray")}} instances determines whether a typed array includes a certain value among its entries, returning `true` or `false` as appropriate. This method has the same algorithm as {{jsxref("Array.prototype.includes()")}}. {{EmbedInteractiveExample("pages/js/typedarray-includes.html")}} ## Syntax ```js-nolint includes(searchElement) includes(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : The value to search for. - `fromIndex` {{optional_inline}} - : Zero-based index at which to start searching, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). ### Return value A boolean value which is `true` if the value `searchElement` is found within the typed array (or the part of the typed array indicated by the index `fromIndex`, if specified). ## Description See {{jsxref("Array.prototype.includes()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Using includes() ```js const uint8 = new Uint8Array([1, 2, 3]); uint8.includes(2); // true uint8.includes(4); // false uint8.includes(3, 3); // false // NaN handling (only true for Float32 and Float64) new Uint8Array([NaN]).includes(NaN); // false, since the NaN passed to the constructor gets converted to 0 new Float32Array([NaN]).includes(NaN); // true; new Float64Array([NaN]).includes(NaN); // true; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.includes` 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("TypedArray.prototype.indexOf()")}} - {{jsxref("TypedArray.prototype.find()")}} - {{jsxref("TypedArray.prototype.findIndex()")}} - {{jsxref("Array.prototype.includes()")}} - {{jsxref("String.prototype.includes()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/toreversed/index.md
--- title: TypedArray.prototype.toReversed() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/toReversed page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.toReversed --- {{JSRef}} The **`toReversed()`** method of {{jsxref("TypedArray")}} instances is the [copying](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#copying_methods_and_mutating_methods) counterpart of the {{jsxref("TypedArray/reverse", "reverse()")}} method. It returns a new typed array with the elements in reversed order. This method has the same algorithm as {{jsxref("Array.prototype.toReversed()")}}. ## Syntax ```js-nolint toReversed() ``` ### Parameters None. ### Return value A new typed array containing the elements in reversed order. ## Description See {{jsxref("Array.prototype.toReversed()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Using toReversed() ```js const uint8 = new Uint8Array([1, 2, 3]); const reversedUint8 = uint8.toReversed(); console.log(reversedUint8); // Uint8Array [3, 2, 1] console.log(uint8); // Uint8Array [1, 2, 3] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.toReversed` in `core-js`](https://github.com/zloirock/core-js#change-array-by-copy) - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("TypedArray.prototype.reverse()")}} - {{jsxref("TypedArray.prototype.toSorted()")}} - {{jsxref("TypedArray.prototype.with()")}} - {{jsxref("Array.prototype.toReversed()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/length/index.md
--- title: TypedArray.prototype.length slug: Web/JavaScript/Reference/Global_Objects/TypedArray/length page-type: javascript-instance-accessor-property browser-compat: javascript.builtins.TypedArray.length --- {{JSRef}} The **`length`** accessor property of {{jsxref("TypedArray")}} instances returns the length (in elements) of this typed array. {{EmbedInteractiveExample("pages/js/typedarray-length.html", "shorter")}} ## Description The `length` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when a _TypedArray_ is constructed and cannot be changed. If the _TypedArray_ is not specifying a `byteOffset` or a `length`, the length of the referenced {{jsxref("ArrayBuffer")}} will be returned. _TypedArray_ is one of the [TypedArray objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#typedarray_objects). ## Examples ### Using the `length` property ```js const buffer = new ArrayBuffer(8); let uint8 = new Uint8Array(buffer); uint8.length; // 8 (matches the length of the buffer) uint8 = new Uint8Array(buffer, 1, 5); uint8.length; // 5 (as specified when constructing the Uint8Array) uint8 = new Uint8Array(buffer, 2); uint8.length; // 6 (due to the offset of the constructed Uint8Array) ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("TypedArray")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/set/index.md
--- title: TypedArray.prototype.set() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/set page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.set --- {{JSRef}} The **`set()`** method of {{jsxref("TypedArray")}} instances stores multiple values in the typed array, reading input values from a specified array. {{EmbedInteractiveExample("pages/js/typedarray-set.html")}} ## Syntax ```js-nolint set(array) set(array, targetOffset) set(typedarray) set(typedarray, targetOffset) ``` ### Parameters - `array` - : The array from which to copy values. All values from the source array are copied into the target array, unless the length of the source array plus the target offset exceeds the length of the target array, in which case an exception is thrown. - `typedarray` - : If the source array is a typed array, the two arrays may share the same underlying {{jsxref("ArrayBuffer")}}; the JavaScript engine will intelligently **copy** the source range of the buffer to the destination range. - `targetOffset` {{optional_inline}} - : The offset into the target array at which to begin writing values from the source array. If this value is omitted, 0 is assumed (that is, the source array will overwrite values in the target array starting at index 0). ### Return value None ({{jsxref("undefined")}}). ### Exceptions - {{jsxref("RangeError")}} - : Thrown in one of the following cases: - An element will be stored beyond the end of the typed array, either because `targetOffset` is too large or because `array` or `typedarray` is too large. - `targetOffset` is negative. ## Examples ### Using set() ```js const buffer = new ArrayBuffer(8); const uint8 = new Uint8Array(buffer); uint8.set([1, 2, 3], 3); console.log(uint8); // Uint8Array [ 0, 0, 0, 1, 2, 3, 0, 0 ] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.set` 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")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/find/index.md
--- title: TypedArray.prototype.find() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/find page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.find --- {{JSRef}} The **`find()`** method of {{jsxref("TypedArray")}} instances returns the first element in the provided typed array that satisfies the provided testing function. If no values satisfy the testing function, {{jsxref("undefined")}} is returned. This method has the same algorithm as {{jsxref("Array.prototype.find()")}}. {{EmbedInteractiveExample("pages/js/typedarray-find.html")}} ## Syntax ```js-nolint find(callbackFn) find(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the typed array. 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 in the typed array. - `index` - : The index of the current element being processed in the typed array. - `array` - : The typed array `find()` was called upon. - `thisArg` {{optional_inline}} - : A value to use as `this` when executing `callbackFn`. See [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). ### Return value The first element in the typed array that satisfies the provided testing function. Otherwise, {{jsxref("undefined")}} is returned. ## Description See {{jsxref("Array.prototype.find()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Find a prime number in a typed array The following example finds an element in the typed array that is a prime number (or returns {{jsxref("undefined")}} if there is no prime number). ```js function isPrime(element, index, array) { let start = 2; while (start <= Math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } const uint8 = new Uint8Array([4, 5, 8, 12]); console.log(uint8.find(isPrime)); // 5 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.find` 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("TypedArray.prototype.findIndex()")}} - {{jsxref("TypedArray.prototype.findLast()")}} - {{jsxref("TypedArray.prototype.findLastIndex()")}} - {{jsxref("TypedArray.prototype.includes()")}} - {{jsxref("TypedArray.prototype.filter()")}} - {{jsxref("TypedArray.prototype.every()")}} - {{jsxref("TypedArray.prototype.some()")}} - {{jsxref("Array.prototype.find()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/findindex/index.md
--- title: TypedArray.prototype.findIndex() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/findIndex page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.findIndex --- {{JSRef}} The **`findIndex()`** method of {{jsxref("TypedArray")}} instances returns the index of the first element in a typed array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned. This method has the same algorithm as {{jsxref("Array.prototype.findIndex()")}}. {{EmbedInteractiveExample("pages/js/typedarray-findindex.html")}} ## Syntax ```js-nolint findIndex(callbackFn) findIndex(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the typed array. 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 in the typed array. - `index` - : The index of the current element being processed in the typed array. - `array` - : The typed array `findIndex()` was called upon. - `thisArg` {{optional_inline}} - : A value to use as `this` when executing `callbackFn`. See [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). ### Return value The index of the first element in the typed array that passes the test. Otherwise, `-1`. ## Description See {{jsxref("Array.prototype.findIndex()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Find the index of a prime number in a typed array The following example finds the index of an element in the typed array that is a prime number (or returns `-1` if there is no prime number). ```js function isPrime(element, index, array) { let start = 2; while (start <= Math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } const uint8 = new Uint8Array([4, 6, 8, 12]); const uint16 = new Uint16Array([4, 6, 7, 12]); console.log(uint8.findIndex(isPrime)); // -1, not found console.log(uint16.findIndex(isPrime)); // 2 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.findIndex` 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("TypedArray.prototype.find()")}} - {{jsxref("TypedArray.prototype.findLast()")}} - {{jsxref("TypedArray.prototype.findLastIndex()")}} - {{jsxref("TypedArray.prototype.indexOf()")}} - {{jsxref("TypedArray.prototype.lastIndexOf()")}} - {{jsxref("Array.prototype.findIndex()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/keys/index.md
--- title: TypedArray.prototype.keys() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/keys page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.keys --- {{JSRef}} The **`keys()`** method of {{jsxref("TypedArray")}} instances returns a new _[array iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator)_ object that contains the keys for each index in the typed array. This method has the same algorithm as {{jsxref("Array.prototype.keys()")}}. {{EmbedInteractiveExample("pages/js/typedarray-keys.html")}} ## Syntax ```js-nolint keys() ``` ### Parameters None. ### Return value A new [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator). ## Description See {{jsxref("Array.prototype.keys()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Iteration using for...of loop ```js const arr = new Uint8Array([10, 20, 30, 40, 50]); const arrKeys = arr.keys(); for (const n of arrKeys) { console.log(n); } ``` ### Alternative iteration ```js const arr = new Uint8Array([10, 20, 30, 40, 50]); const arrKeys = arr.keys(); console.log(arrKeys.next().value); // 0 console.log(arrKeys.next().value); // 1 console.log(arrKeys.next().value); // 2 console.log(arrKeys.next().value); // 3 console.log(arrKeys.next().value); // 4 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.keys` 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("TypedArray.prototype.entries()")}} - {{jsxref("TypedArray.prototype.values()")}} - [`TypedArray.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/@@iterator) - {{jsxref("Array.prototype.keys()")}} - [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/every/index.md
--- title: TypedArray.prototype.every() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/every page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.every --- {{JSRef}} The **`every()`** method of {{jsxref("TypedArray")}} instances tests whether all elements in the typed array pass the test implemented by the provided function. It returns a Boolean value. This method has the same algorithm as {{jsxref("Array.prototype.every()")}}. {{EmbedInteractiveExample("pages/js/typedarray-every.html")}} ## Syntax ```js-nolint every(callbackFn) every(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the typed array. 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 in the typed array. - `index` - : The index of the current element being processed in the typed array. - `array` - : The typed array `every()` was called upon. - `thisArg` {{optional_inline}} - : A value to use as `this` when executing `callbackFn`. See [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). ### Return value `true` unless `callbackFn` returns a {{Glossary("falsy")}} value for a typed array element, in which case `false` is immediately returned. ## Description See {{jsxref("Array.prototype.every()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Testing size of all typed array elements The following example tests whether all elements in the typed array are 10 or bigger. ```js function isBigEnough(element, index, array) { return element >= 10; } new Uint8Array([12, 5, 8, 130, 44]).every(isBigEnough); // false new Uint8Array([12, 54, 18, 130, 44]).every(isBigEnough); // true ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.every` 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("TypedArray.prototype.forEach()")}} - {{jsxref("TypedArray.prototype.some()")}} - {{jsxref("TypedArray.prototype.find()")}} - {{jsxref("Array.prototype.every()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/bytes_per_element/index.md
--- title: TypedArray.BYTES_PER_ELEMENT slug: Web/JavaScript/Reference/Global_Objects/TypedArray/BYTES_PER_ELEMENT page-type: javascript-static-data-property browser-compat: javascript.builtins.TypedArray.BYTES_PER_ELEMENT --- {{JSRef}} The **`TypedArray.BYTES_PER_ELEMENT`** static data property represents the size in bytes of each element in a typed array. {{EmbedInteractiveExample("pages/js/typedarray-bytes-per-element.html", "shorter")}} ## Value A number whose value depends on the type of `TypedArray`. {{js_property_attributes(0, 0, 0)}} ## Description `TypedArray` objects differ from each other in the number of bytes per element and in the way the bytes are interpreted. The `BYTES_PER_ELEMENT` constant contains the number of bytes each element in the given `TypedArray` has. The `BYTES_PER_ELEMENT` property is both an _instance property_ and a _static property_. It's available on both `TypedArray` subclass constructors and on instances of those constructors. As an instance property, `BYTES_PER_ELEMENT` is defined on the constructor's `prototype`. ```js console.log(Object.hasOwn(Int8Array.prototype, "BYTES_PER_ELEMENT")); // true ``` ## Examples ### Using BYTES_PER_ELEMENT As a static property: ```js Int8Array.BYTES_PER_ELEMENT; // 1 Uint8Array.BYTES_PER_ELEMENT; // 1 Uint8ClampedArray.BYTES_PER_ELEMENT; // 1 Int16Array.BYTES_PER_ELEMENT; // 2 Uint16Array.BYTES_PER_ELEMENT; // 2 Int32Array.BYTES_PER_ELEMENT; // 4 Uint32Array.BYTES_PER_ELEMENT; // 4 Float32Array.BYTES_PER_ELEMENT; // 4 Float64Array.BYTES_PER_ELEMENT; // 8 BigInt64Array.BYTES_PER_ELEMENT; // 8 BigUint64Array.BYTES_PER_ELEMENT; // 8 ``` As an instance property: ```js new Int8Array([]).BYTES_PER_ELEMENT; // 1 new Uint8Array([]).BYTES_PER_ELEMENT; // 1 new Uint8ClampedArray([]).BYTES_PER_ELEMENT; // 1 new Int16Array([]).BYTES_PER_ELEMENT; // 2 new Uint16Array([]).BYTES_PER_ELEMENT; // 2 new Int32Array([]).BYTES_PER_ELEMENT; // 4 new Uint32Array([]).BYTES_PER_ELEMENT; // 4 new Float32Array([]).BYTES_PER_ELEMENT; // 4 new Float64Array([]).BYTES_PER_ELEMENT; // 8 new BigInt64Array([]).BYTES_PER_ELEMENT; // 8 new BigUint64Array([]).BYTES_PER_ELEMENT; // 8 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("TypedArray")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/findlastindex/index.md
--- title: TypedArray.prototype.findLastIndex() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/findLastIndex page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.findLastIndex --- {{JSRef}} The **`findLastIndex()`** method of {{jsxref("TypedArray")}} instances iterates the typed array in reverse order and returns the index of the first element that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned. This method has the same algorithm as {{jsxref("Array.prototype.findLastIndex()")}}. {{EmbedInteractiveExample("pages/js/typedarray-findlastindex.html")}} ## Syntax ```js-nolint findLastIndex(callbackFn) findLastIndex(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the typed array. 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 in the typed array. - `index` - : The index of the current element being processed in the typed array. - `array` - : The typed array `findLastIndex()` was called upon. - `thisArg` {{optional_inline}} - : A value to use as `this` when executing `callbackFn`. See [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). ### Return value The index of the last (highest-index) element in the typed array that passes the test. Otherwise `-1` if no matching element is found. ## Description See {{jsxref("Array.prototype.findLastIndex()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Find the index of the last prime number in a typed array The following example returns the index of the last element in the typed array that is a prime number, or `-1` if there is no prime number. ```js function isPrime(element) { if (element % 2 === 0 || element < 2) { return false; } for (let factor = 3; factor <= Math.sqrt(element); factor += 2) { if (element % factor === 0) { return false; } } return true; } let uint8 = new Uint8Array([4, 6, 8, 12]); console.log(uint8.findLastIndex(isPrime)); // -1 (no primes in array) uint8 = new Uint8Array([4, 5, 7, 8, 9, 11, 12]); console.log(uint8.findLastIndex(isPrime)); // 5 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.findLastIndex` in `core-js`](https://github.com/zloirock/core-js#array-find-from-last) - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("TypedArray")}} - {{jsxref("TypedArray.prototype.find()")}} - {{jsxref("TypedArray.prototype.findIndex()")}} - {{jsxref("TypedArray.prototype.findLast()")}} - {{jsxref("TypedArray.prototype.indexOf()")}} - {{jsxref("TypedArray.prototype.lastIndexOf()")}} - {{jsxref("Array.prototype.findLastIndex()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/lastindexof/index.md
--- title: TypedArray.prototype.lastIndexOf() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/lastIndexOf page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.lastIndexOf --- {{JSRef}} The **`lastIndexOf()`** method of {{jsxref("TypedArray")}} instances returns the last index at which a given element can be found in the typed array, or -1 if it is not present. The typed array is searched backwards, starting at `fromIndex`. This method has the same algorithm as {{jsxref("Array.prototype.lastIndexOf()")}}. {{EmbedInteractiveExample("pages/js/typedarray-lastindexof.html")}} ## Syntax ```js-nolint lastIndexOf(searchElement) lastIndexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the typed array. - `fromIndex` {{optional_inline}} - : Zero-based index at which to start searching backwards, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). ### Return value The last index of `searchElement` in the typed array; `-1` if not found. ## Description See {{jsxref("Array.prototype.lastIndexOf()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Using lastIndexOf() ```js const uint8 = new Uint8Array([2, 5, 9, 2]); uint8.lastIndexOf(2); // 3 uint8.lastIndexOf(7); // -1 uint8.lastIndexOf(2, 3); // 3 uint8.lastIndexOf(2, 2); // 0 uint8.lastIndexOf(2, -2); // 0 uint8.lastIndexOf(2, -1); // 3 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.lastIndexOf` 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("TypedArray.prototype.findIndex()")}} - {{jsxref("TypedArray.prototype.findLastIndex()")}} - {{jsxref("TypedArray.prototype.indexOf()")}} - {{jsxref("Array.prototype.lastIndexOf()")}} - {{jsxref("String.prototype.lastIndexOf()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/bytelength/index.md
--- title: TypedArray.prototype.byteLength slug: Web/JavaScript/Reference/Global_Objects/TypedArray/byteLength page-type: javascript-instance-accessor-property browser-compat: javascript.builtins.TypedArray.byteLength --- {{JSRef}} The **`byteLength`** accessor property of {{jsxref("TypedArray")}} instances returns the length (in bytes) of this typed array. {{EmbedInteractiveExample("pages/js/typedarray-bytelength.html", "shorter")}} ## 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 a _TypedArray_ is constructed and cannot be changed. If the _TypedArray_ is not specifying a `byteOffset` or a `length`, the `length` of the referenced `ArrayBuffer` will be returned. _TypedArray_ is one of the [TypedArray objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#typedarray_objects). ## Examples ### Using the byteLength property ```js const buffer = new ArrayBuffer(8); const uint8 = new Uint8Array(buffer); uint8.byteLength; // 8 (matches the byteLength of the buffer) const uint8newLength = new Uint8Array(buffer, 1, 5); uint8newLength.byteLength; // 5 (as specified when constructing the Uint8Array) const uint8offSet = new Uint8Array(buffer, 2); uint8offSet.byteLength; // 6 (due to the offset of the constructed Uint8Array) ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("TypedArray")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/reduce/index.md
--- title: TypedArray.prototype.reduce() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/reduce page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.reduce --- {{JSRef}} The **`reduce()`** method of {{jsxref("TypedArray")}} instances executes a user-supplied "reducer" callback function on each element of the typed array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the typed array is a single value. This method has the same algorithm as {{jsxref("Array.prototype.reduce()")}}. {{EmbedInteractiveExample("pages/js/typedarray-reduce.html")}} ## Syntax ```js-nolint reduce(callbackFn) reduce(callbackFn, initialValue) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the typed array. 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 `array[0]`. - `currentValue` - : The value of the current element. On the first call, its value is `array[0]` if `initialValue` is specified; otherwise its value is `array[1]`. - `currentIndex` - : The index position of `currentValue` in the typed array. On the first call, its value is `0` if `initialValue` is specified, otherwise `1`. - `array` - : The typed array `reduce()` was called upon. - `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 value in the typed array as `currentValue`. If `initialValue` is _not_ specified, `accumulator` is initialized to the first value in the typed array, and `callbackFn` starts executing with the second value in the typed array as `currentValue`. In this case, if the typed array 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 typed array. ### Exceptions - {{jsxref("TypeError")}} - : Thrown if the typed array contains no elements and `initialValue` is not provided. ## Description See {{jsxref("Array.prototype.reduce()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Sum up all values within an array ```js const total = new Uint8Array([0, 1, 2, 3]).reduce((a, b) => a + b); // total === 6 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.reduce` 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("TypedArray.prototype.map()")}} - {{jsxref("TypedArray.prototype.reduceRight()")}} - {{jsxref("Array.prototype.reduce()")}} - {{jsxref("Object.groupBy()")}} - {{jsxref("Map.groupBy()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/tosorted/index.md
--- title: TypedArray.prototype.toSorted() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/toSorted page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.toSorted --- {{JSRef}} The **`toSorted()`** method of {{jsxref("TypedArray")}} instances is the [copying](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#copying_methods_and_mutating_methods) version of the {{jsxref("TypedArray/sort", "sort()")}} method. It returns a new typed array with the elements sorted in ascending order. This method has the same algorithm as {{jsxref("Array.prototype.toSorted()")}}, except that it sorts the values numerically instead of as strings by default. ## Syntax ```js-nolint toSorted() toSorted(compareFn) ``` ### Parameters - `compareFn` {{optional_inline}} - : Specifies a function that defines the sort order. If omitted, the typed array elements are sorted according to numeric value. - `a` - : The first element for comparison. - `b` - : The second element for comparison. ### Return value A new typed array with the elements sorted in ascending order. ## Description See {{jsxref("Array.prototype.toSorted()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Sorting an array For more examples, see also the {{jsxref("Array.prototype.sort()")}} method. ```js const numbers = new Uint8Array([40, 1, 5, 200]); const numberSorted = numbers.toSorted(); console.log(numberSorted); // Uint8Array [ 1, 5, 40, 200 ] // Unlike plain Arrays, a compare function is not required // to sort the numbers numerically. console.log(numbers); // Uint8Array [ 40, 1, 5, 200 ] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.toSorted` in `core-js`](https://github.com/zloirock/core-js#change-array-by-copy) - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("TypedArray.prototype.sort()")}} - {{jsxref("TypedArray.prototype.toReversed()")}} - {{jsxref("TypedArray.prototype.with()")}} - {{jsxref("Array.prototype.toSorted()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/of/index.md
--- title: TypedArray.of() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/of page-type: javascript-static-method browser-compat: javascript.builtins.TypedArray.of --- {{JSRef}} The **`TypedArray.of()`** static method creates a new [typed array](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#typedarray_objects) from a variable number of arguments. This method is nearly the same as {{jsxref("Array.of()")}}. {{EmbedInteractiveExample("pages/js/typedarray-of.html", "shorter")}} ## Syntax ```js-nolint TypedArray.of() TypedArray.of(element1) TypedArray.of(element1, element2) TypedArray.of(element1, element2, /* …, */ elementN) ``` Where `TypedArray` is one of: - {{jsxref("Int8Array")}} - {{jsxref("Uint8Array")}} - {{jsxref("Uint8ClampedArray")}} - {{jsxref("Int16Array")}} - {{jsxref("Uint16Array")}} - {{jsxref("Int32Array")}} - {{jsxref("Uint32Array")}} - {{jsxref("Float32Array")}} - {{jsxref("Float64Array")}} - {{jsxref("BigInt64Array")}} - {{jsxref("BigUint64Array")}} ### Parameters - `element1`, …, `elementN` - : Elements used to create the typed array. ### Return value A new {{jsxref("TypedArray")}} instance. ## Description See {{jsxref("Array.of()")}} for more details. There are some subtle distinctions between {{jsxref("Array.of()")}} and `TypedArray.of()`: - If the `this` value passed to `TypedArray.of()` is not a constructor, `TypedArray.from()` will throw a {{jsxref("TypeError")}}, while `Array.of()` defaults to creating a new {{jsxref("Array")}}. - `TypedArray.of()` uses `[[Set]]` while `Array.of()` uses `[[DefineOwnProperty]]`. Hence, when working with {{jsxref("Proxy")}} objects, it calls [`handler.set()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/set) to create new elements rather than [`handler.defineProperty()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/defineProperty). ## Examples ### Using of() ```js Uint8Array.of(1); // Uint8Array [ 1 ] Int8Array.of("1", "2", "3"); // Int8Array [ 1, 2, 3 ] Float32Array.of(1, 2, 3); // Float32Array [ 1, 2, 3 ] Int16Array.of(undefined); // Int16Array [ 0 ] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.of` 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("TypedArray.from()")}} - {{jsxref("Array.of()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/values/index.md
--- title: TypedArray.prototype.values() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/values page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.values --- {{JSRef}} The **`values()`** method of {{jsxref("TypedArray")}} instances returns a new _[array iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator)_ object that iterates the value of each item in the typed array. This method has the same algorithm as {{jsxref("Array.prototype.values()")}}. {{EmbedInteractiveExample("pages/js/typedarray-values.html")}} ## Syntax ```js-nolint values() ``` ### Parameters None. ### Return value A new [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator). ## Description See {{jsxref("Array.prototype.values()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Iteration using for...of loop ```js const arr = new Uint8Array([10, 20, 30, 40, 50]); const values = arr.values(); for (const n of values) { console.log(n); } ``` ### Alternative iteration ```js const arr = new Uint8Array([10, 20, 30, 40, 50]); const values = arr.values(); console.log(values.next().value); // 10 console.log(values.next().value); // 20 console.log(values.next().value); // 30 console.log(values.next().value); // 40 console.log(values.next().value); // 50 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.values` 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("TypedArray.prototype.entries()")}} - {{jsxref("TypedArray.prototype.keys()")}} - [`TypedArray.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/@@iterator) - {{jsxref("Array.prototype.values()")}} - [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/with/index.md
--- title: TypedArray.prototype.with() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/with page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.with --- {{JSRef}} The **`with()`** method of {{jsxref("TypedArray")}} instances is the [copying](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#copying_methods_and_mutating_methods) version of using the [bracket notation](/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#bracket_notation) to change the value of a given index. It returns a new typed array with the element at the given index replaced with the given value. This method has the same algorithm as {{jsxref("Array.prototype.with()")}}. ## Syntax ```js-nolint arrayInstance.with(index, value) ``` ### Parameters - `index` - : Zero-based index at which to change the typed array, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). - `value` - : Any value to be assigned to the given index. ### Return value A new typed array with the element at `index` replaced with `value`. ### Exceptions - {{jsxref("RangeError")}} - : Thrown if `index >= array.length` or `index < -array.length`. ## Description See {{jsxref("Array.prototype.with()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Using with() ```js const arr = new Uint8Array([1, 2, 3, 4, 5]); console.log(arr.with(2, 6)); // Uint8Array [1, 2, 6, 4, 5] console.log(arr); // Uint8Array [1, 2, 3, 4, 5] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.with` in `core-js`](https://github.com/zloirock/core-js#change-array-by-copy) - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("TypedArray.prototype.toReversed()")}} - {{jsxref("TypedArray.prototype.toSorted()")}} - {{jsxref("TypedArray.prototype.at()")}} - {{jsxref("Array.prototype.with()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/@@iterator/index.md
--- title: TypedArray.prototype[@@iterator]() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/@@iterator page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.@@iterator --- {{JSRef}} The **`[@@iterator]()`** method of {{jsxref("TypedArray")}} instances implements the [iterable protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) and allows typed arrays to be consumed by most syntaxes expecting iterables, such as the [spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and {{jsxref("Statements/for...of", "for...of")}} loops. It returns an [array iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) that yields the value of each index in the typed array. The initial value of this property is the same function object as the initial value of the {{jsxref("TypedArray.prototype.values")}} property. {{EmbedInteractiveExample("pages/js/typedarray-prototype-@@iterator.html")}} ## Syntax ```js-nolint typedArray[Symbol.iterator]() ``` ### Parameters None. ### Return value The same return value as {{jsxref("TypedArray.prototype.values()")}}: a new [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) that yields the value of each index in the typed array. ## Examples ### Iteration using for...of loop Note that you seldom need to call this method directly. The existence of the `@@iterator` method makes typed arrays [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 arr = new Uint8Array([10, 20, 30, 40, 50]); for (const n of arr) { console.log(n); } ``` ### Manually hand-rolling the iterator You may still manually call the `next()` method of the returned iterator object to achieve maximum control over the iteration process. ```js const arr = new Uint8Array([10, 20, 30, 40, 50]); const arrIter = arr[Symbol.iterator](); console.log(arrIter.next().value); // 10 console.log(arrIter.next().value); // 20 console.log(arrIter.next().value); // 30 console.log(arrIter.next().value); // 40 console.log(arrIter.next().value); // 50 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype[@@iterator]` 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("TypedArray.prototype.entries()")}} - {{jsxref("TypedArray.prototype.keys()")}} - {{jsxref("TypedArray.prototype.values()")}} - {{jsxref("Symbol.iterator")}} - [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/some/index.md
--- title: TypedArray.prototype.some() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/some page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.some --- {{JSRef}} The **`some()`** method of {{jsxref("TypedArray")}} instances tests whether at least one element in the typed array passes the test implemented by the provided function. It returns true if, in the typed array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the typed array. This method has the same algorithm as {{jsxref("Array.prototype.some()")}}. {{EmbedInteractiveExample("pages/js/typedarray-some.html")}} ## Syntax ```js-nolint some(callbackFn) some(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the typed array. 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 in the typed array. - `index` - : The index of the current element being processed in the typed array. - `array` - : The typed array `some()` was called upon. - `thisArg` {{optional_inline}} - : A value to use as `this` when executing `callbackFn`. See [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). ### Return value `false` unless `callbackFn` returns a {{Glossary("truthy")}} value for a typed array element, in which case `true` is immediately returned. ## Description See {{jsxref("Array.prototype.some()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Testing size of all typed array elements The following example tests whether any element in the typed array is bigger than 10. ```js function isBiggerThan10(element, index, array) { return element > 10; } new Uint8Array([2, 5, 8, 1, 4]).some(isBiggerThan10); // false new Uint8Array([12, 5, 8, 1, 4]).some(isBiggerThan10); // true ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.some` 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("TypedArray.prototype.every()")}} - {{jsxref("TypedArray.prototype.forEach()")}} - {{jsxref("TypedArray.prototype.find()")}} - {{jsxref("TypedArray.prototype.includes()")}} - {{jsxref("Array.prototype.some()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/foreach/index.md
--- title: TypedArray.prototype.forEach() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/forEach page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.forEach --- {{JSRef}} The **`forEach()`** method of {{jsxref("TypedArray")}} instances executes a provided function once for each typed array element. This method has the same algorithm as {{jsxref("Array.prototype.forEach()")}}. {{EmbedInteractiveExample("pages/js/typedarray-foreach.html")}} ## Syntax ```js-nolint forEach(callbackFn) forEach(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the typed array. Its return value is discarded. The function is called with the following arguments: - `element` - : The current element being processed in the typed array. - `index` - : The index of the current element being processed in the typed array. - `array` - : The typed array `forEach()` was called upon. - `thisArg` {{optional_inline}} - : A value to use as `this` when executing `callbackFn`. See [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). ### Return value None ({{jsxref("undefined")}}). ## Description See {{jsxref("Array.prototype.forEach()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Logging the contents of a typed array The following code logs a line for each element in a typed array: ```js function logArrayElements(element, index, array) { console.log(`a[${index}] = ${element}`); } new Uint8Array([0, 1, 2, 3]).forEach(logArrayElements); // Logs: // a[0] = 0 // a[1] = 1 // a[2] = 2 // a[3] = 3 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.forEach` 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("TypedArray.prototype.find()")}} - {{jsxref("TypedArray.prototype.map()")}} - {{jsxref("TypedArray.prototype.filter()")}} - {{jsxref("TypedArray.prototype.every()")}} - {{jsxref("TypedArray.prototype.some()")}} - {{jsxref("Array.prototype.forEach()")}} - {{jsxref("Map.prototype.forEach()")}} - {{jsxref("Set.prototype.forEach()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/fill/index.md
--- title: TypedArray.prototype.fill() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/fill page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.fill --- {{JSRef}} The **`fill()`** method of {{jsxref("TypedArray")}} instances changes all elements within a range of indices in a typed array to a static value. It returns the modified typed array. This method has the same algorithm as {{jsxref("Array.prototype.fill()")}}. {{EmbedInteractiveExample("pages/js/typedarray-fill.html", "shorter")}} ## Syntax ```js-nolint fill(value) fill(value, start) fill(value, start, end) ``` ### Parameters - `value` - : Value to fill the typed array with. - `start` {{optional_inline}} - : Zero-based index at which to start filling, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). - `end` {{optional_inline}} - : Zero-based index at which to end filling, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). `fill()` fills up to but not including `end`. ### Return value The modified typed array, filled with `value`. ## Description See {{jsxref("Array.prototype.fill()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Using fill() ```js new Uint8Array([1, 2, 3]).fill(4); // Uint8Array [4, 4, 4] new Uint8Array([1, 2, 3]).fill(4, 1); // Uint8Array [1, 4, 4] new Uint8Array([1, 2, 3]).fill(4, 1, 2); // Uint8Array [1, 4, 3] new Uint8Array([1, 2, 3]).fill(4, 1, 1); // Uint8Array [1, 2, 3] new Uint8Array([1, 2, 3]).fill(4, -3, -2); // Uint8Array [4, 2, 3] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.fill` 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("Array.prototype.fill()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/tolocalestring/index.md
--- title: TypedArray.prototype.toLocaleString() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/toLocaleString page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.toLocaleString --- {{JSRef}} The **`toLocaleString()`** method of {{jsxref("TypedArray")}} instances returns a string representing the elements of the typed array. The elements are converted to strings using their `toLocaleString` methods and these strings are separated by a locale-specific string (such as a comma ","). This method has the same algorithm as {{jsxref("Array.prototype.toLocaleString()")}}. {{EmbedInteractiveExample("pages/js/typedarray-tolocalestring.html")}} ## Syntax ```js-nolint toLocaleString() toLocaleString(locales) toLocaleString(locales, options) ``` ### Parameters - `locales` {{optional_inline}} - : A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [the parameter description on the `Intl` main page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument). - `options` {{optional_inline}} - : An object with configuration properties. See {{jsxref("Number.prototype.toLocaleString()")}}. ### Return value A string representing the elements of the typed array. ## Description See {{jsxref("Array.prototype.toLocaleString()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Using toLocaleString() ```js const uint = new Uint32Array([2000, 500, 8123, 12, 4212]); uint.toLocaleString(); // if run in a de-DE locale // "2.000,500,8.123,12,4.212" uint.toLocaleString("en-US"); // "2,000,500,8,123,12,4,212" uint.toLocaleString("ja-JP", { style: "currency", currency: "JPY" }); // "οΏ₯2,000,οΏ₯500,οΏ₯8,123,οΏ₯12,οΏ₯4,212" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide - {{jsxref("TypedArray")}} - {{jsxref("TypedArray.prototype.toString()")}} - {{jsxref("Array.prototype.toLocaleString()")}} - {{jsxref("Intl")}} - {{jsxref("Intl.ListFormat")}} - {{jsxref("Number.prototype.toLocaleString()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/sort/index.md
--- title: TypedArray.prototype.sort() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/sort page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.sort --- {{JSRef}} The **`sort()`** method of {{jsxref("TypedArray")}} instances sorts the elements of a typed array _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_ and returns the reference to the same typed array, now sorted. This method has the same algorithm as {{jsxref("Array.prototype.sort()")}}, except that it sorts the values numerically instead of as strings by default. {{EmbedInteractiveExample("pages/js/typedarray-sort.html", "shorter")}} ## Syntax ```js-nolint sort() sort(compareFn) ``` ### Parameters - `compareFn` {{optional_inline}} - : A function that defines the sort order. The return value should be a number whose sign indicates the relative order of the two elements: negative if `a` is less than `b`, positive if `a` is greater than `b`, and zero if they are equal. `NaN` is treated as `0`. The function is called with the following arguments: - `a` - : The first element for comparison. Will never be `undefined`. - `b` - : The second element for comparison. Will never be `undefined`. If omitted, the typed array elements are sorted according to numeric value. ### Return value The reference to the original typed array, now sorted. Note that the typed array is sorted _[in place](https://en.wikipedia.org/wiki/In-place_algorithm)_, and no copy is made. ## Description See {{jsxref("Array.prototype.sort()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Using sort() For more examples, see also the {{jsxref("Array.prototype.sort()")}} method. ```js let numbers = new Uint8Array([40, 1, 5, 200]); numbers.sort(); // Uint8Array [ 1, 5, 40, 200 ] // Unlike plain Arrays, a compare function is not required // to sort the numbers numerically. // Regular Arrays require a compare function to sort numerically: numbers = [40, 1, 5, 200]; numbers.sort(); // [1, 200, 40, 5] numbers.sort((a, b) => a - b); // compare numbers // [ 1, 5, 40, 200 ] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.sort` with modern behavior like stable sort 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("TypedArray.prototype.reverse()")}} - {{jsxref("TypedArray.prototype.toSorted()")}} - {{jsxref("Array.prototype.sort()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/join/index.md
--- title: TypedArray.prototype.join() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/join page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.join --- {{JSRef}} The **`join()`** method of {{jsxref("TypedArray")}} instances creates and returns a new string by concatenating all of the elements in this typed array, separated by commas or a specified separator string. If the typed array has only one item, then that item will be returned without using the separator. This method has the same algorithm as {{jsxref("Array.prototype.join()")}}. {{EmbedInteractiveExample("pages/js/typedarray-join.html")}} ## Syntax ```js-nolint join() join(separator) ``` ### Parameters - `separator` {{optional_inline}} - : A string to separate each pair of adjacent elements of the typed array. If omitted, the typed array elements are separated with a comma (","). ### Return value A string with all typed array elements joined. If `array.length` is `0`, the empty string is returned. ## Description See {{jsxref("Array.prototype.join()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Using join() ```js const uint8 = new Uint8Array([1, 2, 3]); uint8.join(); // '1,2,3' uint8.join(" / "); // '1 / 2 / 3' uint8.join(""); // '123' ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.join` 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("TypedArray.prototype.toString()")}} - {{jsxref("Array.prototype.join()")}} - {{jsxref("String.prototype.split()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/@@species/index.md
--- title: TypedArray[@@species] slug: Web/JavaScript/Reference/Global_Objects/TypedArray/@@species page-type: javascript-static-accessor-property browser-compat: javascript.builtins.TypedArray.@@species --- {{JSRef}} The **`TypedArray[@@species]`** static accessor property returns the constructor used to construct return values from typed array 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 TypedArray[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 typed array methods that create new typed arrays. ## Description The `@@species` accessor property returns the default constructor for [typed array](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#typedarray_objects) objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class TypedArray { 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 SubTypedArray extends Int8Array {} SubTypedArray[Symbol.species] === SubTypedArray; // true ``` When calling typed array methods that do not mutate the existing array but return a new array instance (for example, [`filter()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/filter) and [`map()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/map)), the array's `constructor[@@species]` will be accessed. The returned constructor will be used to construct the return value of the typed array method. However, unlike [`Array[@@species]`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@species), when using `@@species` to create new typed arrays, the language will make sure that the newly created array is a proper typed array and has the same content type as the original array β€” for example, you can't create a {{jsxref("BigInt64Array")}} from a {{jsxref("Float64Array")}}, or create a non-BigInt array from a BigInt array. Doing so throws a {{jsxref("TypeError")}}. ```js class BadArray extends Int8Array { static get [Symbol.species]() { return Array; } } new BadArray(1).map(() => 0); // TypeError: Method %TypedArray%.prototype.map called on incompatible receiver [object Array] class BadArray2 extends Int8Array { static get [Symbol.species]() { return BigInt64Array; } } new BadArray2(1).map(() => 0n); // TypeError: TypedArray.prototype.map constructed typed array of different content type from |this| ``` > **Note:** Due to a bug in both [SpiderMonkey](https://bugzil.la/1640194) and V8, the content type match is not checked. Only Safari will throw a {{jsxref("TypeError")}} in the second example. ## Examples ### Species in ordinary objects The `@@species` property returns the default constructor function, which is one of the typed array constructors itself for any given [typed array](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#typedarray_objects) constructor. ```js Int8Array[Symbol.species]; // function Int8Array() Uint8Array[Symbol.species]; // function Uint8Array() Float32Array[Symbol.species]; // function Float32Array() ``` ### Species in derived objects In an instance of a custom `TypedArray` subclass, such as `MyTypedArray`, the `MyTypedArray` species is the `MyTypedArray` constructor. However, you might want to overwrite this, in order to return a parent [typed array](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#typedarray_objects) object in your derived class methods: ```js class MyTypedArray extends Uint8Array { // Overwrite MyTypedArray species to the parent Uint8Array constructor static get [Symbol.species]() { return Uint8Array; } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("TypedArray")}} - {{jsxref("Symbol.species")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/indexof/index.md
--- title: TypedArray.prototype.indexOf() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/indexOf page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.indexOf --- {{JSRef}} The **`indexOf()`** method of {{jsxref("TypedArray")}} instances returns the first index at which a given element can be found in the typed array, or -1 if it is not present. This method has the same algorithm as {{jsxref("Array.prototype.indexOf()")}}. {{EmbedInteractiveExample("pages/js/typedarray-indexof.html")}} ## Syntax ```js-nolint indexOf(searchElement) indexOf(searchElement, fromIndex) ``` ### Parameters - `searchElement` - : Element to locate in the typed array. - `fromIndex` {{optional_inline}} - : Zero-based index at which to start searching, [converted to an integer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#integer_conversion). ### Return value The first index of `searchElement` in the typed array; `-1` if not found. ## Description See {{jsxref("Array.prototype.indexOf()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Using indexOf() ```js const uint8 = new Uint8Array([2, 5, 9]); uint8.indexOf(2); // 0 uint8.indexOf(7); // -1 uint8.indexOf(9, 2); // 2 uint8.indexOf(2, -1); // -1 uint8.indexOf(2, -3); // 0 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.indexOf` 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("TypedArray.prototype.findIndex()")}} - {{jsxref("TypedArray.prototype.findLastIndex()")}} - {{jsxref("TypedArray.prototype.lastIndexOf()")}} - {{jsxref("Array.prototype.indexOf()")}} - {{jsxref("String.prototype.indexOf()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/filter/index.md
--- title: TypedArray.prototype.filter() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/filter page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.filter --- {{JSRef}} The **`filter()`** method of {{jsxref("TypedArray")}} instances creates a copy of a portion of a given typed array, filtered down to just the elements from the given typed array that pass the test implemented by the provided function. This method has the same algorithm as {{jsxref("Array.prototype.filter()")}}. {{EmbedInteractiveExample("pages/js/typedarray-filter.html")}} ## Syntax ```js-nolint filter(callbackFn) filter(callbackFn, thisArg) ``` ### Parameters - `callbackFn` - : A function to execute for each element in the typed array. It should return a [truthy](/en-US/docs/Glossary/Truthy) value to keep the element in the resulting typed array, and a [falsy](/en-US/docs/Glossary/Falsy) value otherwise. The function is called with the following arguments: - `element` - : The current element being processed in the typed array. - `index` - : The index of the current element being processed in the typed array. - `array` - : The typed array `filter()` was called upon. - `thisArg` {{optional_inline}} - : A value to use as `this` when executing `callbackFn`. See [iterative methods](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#iterative_methods). ### Return value A copy of the given typed array containing just the elements that pass the test. If no elements pass the test, an empty typed array is returned. ## Description See {{jsxref("Array.prototype.filter()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Filtering out all small values The following example uses `filter()` to create a filtered typed array that has all elements with values less than 10 removed. ```js function isBigEnough(element, index, array) { return element >= 10; } new Uint8Array([12, 5, 8, 130, 44]).filter(isBigEnough); // Uint8Array [ 12, 130, 44 ] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.filter` 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("TypedArray.prototype.forEach()")}} - {{jsxref("TypedArray.prototype.every()")}} - {{jsxref("TypedArray.prototype.map()")}} - {{jsxref("TypedArray.prototype.some()")}} - {{jsxref("TypedArray.prototype.reduce()")}} - {{jsxref("Array.prototype.filter()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray
data/mdn-content/files/en-us/web/javascript/reference/global_objects/typedarray/entries/index.md
--- title: TypedArray.prototype.entries() slug: Web/JavaScript/Reference/Global_Objects/TypedArray/entries page-type: javascript-instance-method browser-compat: javascript.builtins.TypedArray.entries --- {{JSRef}} The **`entries()`** method of {{jsxref("TypedArray")}} instances returns a new _[array iterator](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator)_ object that contains the key/value pairs for each index in the typed array. This method has the same algorithm as {{jsxref("Array.prototype.entries()")}}. {{EmbedInteractiveExample("pages/js/typedarray-entries.html")}} ## Syntax ```js-nolint entries() ``` ### Parameters None. ### Return value A new [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator). ## Description See {{jsxref("Array.prototype.entries()")}} for more details. This method is not generic and can only be called on typed array instances. ## Examples ### Iteration using for...of loop ```js const array = new Uint8Array([10, 20, 30, 40, 50]); const arrayEntries = arr.entries(); for (const element of arrayEntries) { console.log(element); } ``` ### Alternative iteration ```js const array = new Uint8Array([10, 20, 30, 40, 50]); const arrayEntries = arr.entries(); console.log(arrayEntries.next().value); // [0, 10] console.log(arrayEntries.next().value); // [1, 20] console.log(arrayEntries.next().value); // [2, 30] console.log(arrayEntries.next().value); // [3, 40] console.log(arrayEntries.next().value); // [4, 50] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `TypedArray.prototype.entries` 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("TypedArray.prototype.keys()")}} - {{jsxref("TypedArray.prototype.values()")}} - [`TypedArray.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/@@iterator) - {{jsxref("Array.prototype.entries()")}} - [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/sharedarraybuffer/index.md
--- title: SharedArrayBuffer slug: Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer page-type: javascript-class browser-compat: javascript.builtins.SharedArrayBuffer --- {{JSRef}} The **`SharedArrayBuffer`** object is used to represent a generic raw binary data buffer, similar to the {{jsxref("ArrayBuffer")}} object, but in a way that they can be used to create views on shared memory. A `SharedArrayBuffer` is not a [Transferable Object](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects), unlike an `ArrayBuffer` which is transferable. ## Description To share memory using `SharedArrayBuffer` objects from one agent in the cluster to another (an agent is either the web page's main program or one of its web workers), [`postMessage`](/en-US/docs/Web/API/Worker/postMessage) and [structured cloning](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) is used. The structured clone algorithm accepts `SharedArrayBuffer` objects and typed arrays mapped onto `SharedArrayBuffer` objects. In both cases, the `SharedArrayBuffer` object is transmitted to the receiver resulting in a new, private `SharedArrayBuffer` object in the receiving agent (just as for {{jsxref("ArrayBuffer")}}). However, the shared data block referenced by the two `SharedArrayBuffer` objects is the same data block, and a side effect to the block in one agent will eventually become visible in the other agent. ```js const sab = new SharedArrayBuffer(1024); worker.postMessage(sab); ``` Shared memory can be created and updated simultaneously in workers or the main thread. Depending on the system (the CPU, the OS, the Browser) it can take a while until the change is propagated to all contexts. To synchronize, {{jsxref("Atomics", "atomic", "", 1)}} operations are needed. `SharedArrayBuffer` objects are used by some web APIs, such as: - [`WebGLRenderingContext.bufferData()`](/en-US/docs/Web/API/WebGLRenderingContext/bufferData) - [`WebGLRenderingContext.bufferSubData()`](/en-US/docs/Web/API/WebGLRenderingContext/bufferSubData) - [`WebGL2RenderingContext.getBufferSubData()`](/en-US/docs/Web/API/WebGL2RenderingContext/getBufferSubData) ### Security requirements Shared memory and high-resolution timers were effectively [disabled at the start of 2018](https://blog.mozilla.org/security/2018/01/03/mitigations-landing-new-class-timing-attack/) in light of [Spectre](<https://en.wikipedia.org/wiki/Spectre_(security_vulnerability)>). In 2020, a new, secure approach has been standardized to re-enable shared memory. As a baseline requirement, your document needs to be in a [secure context](/en-US/docs/Web/Security/Secure_Contexts). For top-level documents, two headers need to be set to cross-origin isolate your site: - [`Cross-Origin-Opener-Policy`](/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy) with `same-origin` as value (protects your origin from attackers) - [`Cross-Origin-Embedder-Policy`](/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy) with `require-corp` or `credentialless` as value (protects victims from your origin) ```http Cross-Origin-Opener-Policy: same-origin Cross-Origin-Embedder-Policy: require-corp ``` To check if cross origin isolation has been successful, you can test against the [`crossOriginIsolated`](/en-US/docs/Web/API/crossOriginIsolated) property available to window and worker contexts: ```js const myWorker = new Worker("worker.js"); if (crossOriginIsolated) { const buffer = new SharedArrayBuffer(16); myWorker.postMessage(buffer); } else { const buffer = new ArrayBuffer(16); myWorker.postMessage(buffer); } ``` With these two headers set, `postMessage()` no longer throws for `SharedArrayBuffer` objects and shared memory across threads is therefore available. Nested documents and dedicated workers need to set the [`Cross-Origin-Embedder-Policy`](/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy) header as well, with the same value. No further changes are needed for same-origin nested documents and subresources. Same-site (but cross-origin) nested documents and subresources need to set the [`Cross-Origin-Resource-Policy`](/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy) header with `same-site` as value. And their cross-origin (and cross-site) counterparts need to set the same header with `cross-origin` as value. Note that setting the [`Cross-Origin-Resource-Policy`](/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy) header to any other value than `same-origin` opens up the resource to potential attacks, such as [Spectre](<https://en.wikipedia.org/wiki/Spectre_(security_vulnerability)>). Note that the [`Cross-Origin-Opener-Policy`](/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy) header limits your ability to retain a reference to popups. Direct access between two top-level window contexts essentially only work if they are same-origin and carry the same two headers with the same two values. ### API availability Depending on whether the above security measures are taken, the various memory-sharing APIs have different availabilities: - The `Atomics` object is always available. - `SharedArrayBuffer` objects are in principle always available, but unfortunately the constructor on the global object is hidden, unless the two headers mentioned above are set, for compatibility with web content. There is hope that this restriction can be removed in the future. [`WebAssembly.Memory`](/en-US/docs/WebAssembly/JavaScript_interface/Memory) can still be used to get an instance. - Unless the two headers mentioned above are set, the various `postMessage()` APIs will throw for `SharedArrayBuffer` objects. If they are set, `postMessage()` on `Window` objects and dedicated workers will function and allow for memory sharing. ### WebAssembly shared memory [`WebAssembly.Memory`](/en-US/docs/WebAssembly/JavaScript_interface/Memory) objects can be created with the [`shared`](/en-US/docs/WebAssembly/JavaScript_interface/Memory/Memory#shared) constructor flag. When this flag is set to `true`, the constructed `Memory` object can be shared between workers via `postMessage()`, just like `SharedArrayBuffer`, and the backing [`buffer`](/en-US/docs/WebAssembly/JavaScript_interface/Memory/buffer) of the `Memory` object is a `SharedArrayBuffer`. Therefore, the requirements listed above for sharing a `SharedArrayBuffer` between workers also apply to sharing a `WebAssembly.Memory`. The WebAssembly Threads proposal also defines a new set of [atomic](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#atomic-memory-accesses) instructions. Just as `SharedArrayBuffer` and its methods are unconditionally enabled (and only sharing between threads is gated on the new headers), the WebAssembly atomic instructions are also unconditionally allowed. ### Growing SharedArrayBuffers `SharedArrayBuffer` objects can be made growable by including the `maxByteLength` option when calling the {{jsxref("SharedArrayBuffer/SharedArrayBuffer", "SharedArrayBuffer()")}} constructor. You can query whether a `SharedArrayBuffer` is growable and what its maximum size is by accessing its {{jsxref("SharedArrayBuffer/growable", "growable")}} and {{jsxref("SharedArrayBuffer/maxByteLength", "maxByteLength")}} properties, respectively. You can assign a new size to a growable `SharedArrayBuffer` with a {{jsxref("SharedArrayBuffer/grow", "grow()")}} call. New bytes are initialized to 0. These features make growing `SharedArrayBuffer`s more efficient β€” otherwise, you have to make a copy of the buffer with a new size. It also gives JavaScript parity with WebAssembly in this regard (Wasm linear memory can be resized with [`WebAssembly.Memory.prototype.grow()`](/en-US/docs/WebAssembly/JavaScript_interface/Memory/grow)). For security reasons, `SharedArrayBuffer`s cannot be reduced in size, only grown. ## Constructor - {{jsxref("SharedArrayBuffer/SharedArrayBuffer", "SharedArrayBuffer()")}} - : Creates a new `SharedArrayBuffer` object. ## Static properties - {{jsxref("SharedArrayBuffer/@@species", "SharedArrayBuffer[@@species]")}} - : Returns the constructor used to construct return values from `SharedArrayBuffer` methods. ## Instance properties These properties are defined on `SharedArrayBuffer.prototype` and shared by all `SharedArrayBuffer` instances. - {{jsxref("SharedArrayBuffer.prototype.byteLength")}} - : The size, in bytes, of the array. This is established when the array is constructed and can only be changed using the {{jsxref("SharedArrayBuffer.prototype.grow()")}} method if the `SharedArrayBuffer` is growable. - {{jsxref("Object/constructor", "SharedArrayBuffer.prototype.constructor")}} - : The constructor function that created the instance object. For `SharedArrayBuffer` instances, the initial value is the {{jsxref("SharedArrayBuffer/SharedArrayBuffer", "SharedArrayBuffer")}} constructor. - {{jsxref("SharedArrayBuffer.prototype.growable")}} - : Read-only. Returns `true` if the `SharedArrayBuffer` can be grown, or `false` if not. - {{jsxref("SharedArrayBuffer.prototype.maxByteLength")}} - : The read-only maximum length, in bytes, that the `SharedArrayBuffer` can be grown to. This is established when the array is constructed and cannot be changed. - `SharedArrayBuffer.prototype[@@toStringTag]` - : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"SharedArrayBuffer"`. This property is used in {{jsxref("Object.prototype.toString()")}}. ## Instance methods - {{jsxref("SharedArrayBuffer.prototype.grow()")}} - : Grows the `SharedArrayBuffer` to the specified size, in bytes. - {{jsxref("SharedArrayBuffer.prototype.slice()")}} - : Returns a new `SharedArrayBuffer` whose contents are a copy of this `SharedArrayBuffer`'s bytes from `begin`, inclusive, up to `end`, exclusive. If either `begin` or `end` is negative, it refers to an index from the end of the array, as opposed to from the beginning. ## Examples ### Creating a new SharedArrayBuffer ```js const sab = new SharedArrayBuffer(1024); ``` ### Slicing the SharedArrayBuffer ```js sab.slice(); // SharedArrayBuffer { byteLength: 1024 } sab.slice(2); // SharedArrayBuffer { byteLength: 1022 } sab.slice(-2); // SharedArrayBuffer { byteLength: 2 } sab.slice(0, 1); // SharedArrayBuffer { byteLength: 1 } ``` ### Using it in a WebGL buffer ```js const canvas = document.querySelector("canvas"); const gl = canvas.getContext("webgl"); const buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, sab, gl.STATIC_DRAW); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Atomics")}} - {{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) - [COOP and COEP explained](https://docs.google.com/document/d/1zDlfvfTJ_9e8Jdc8ehuV4zMEu9ySMCiTGMS9y0GU92k/edit) by the Chrome team (2020) - {{HTTPHeader("Cross-Origin-Opener-Policy")}} - {{HTTPHeader("Cross-Origin-Embedder-Policy")}} - {{HTTPHeader("Cross-Origin-Resource-Policy")}} - [`crossOriginIsolated`](/en-US/docs/Web/API/crossOriginIsolated) - [SharedArrayBuffer updates in Android Chrome 88 and Desktop Chrome 92](https://developer.chrome.com/blog/enabling-shared-array-buffer/) on developer.chrome.com (2021)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/sharedarraybuffer
data/mdn-content/files/en-us/web/javascript/reference/global_objects/sharedarraybuffer/growable/index.md
--- title: SharedArrayBuffer.prototype.growable slug: Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/growable page-type: javascript-instance-accessor-property browser-compat: javascript.builtins.SharedArrayBuffer.growable --- {{JSRef}} The **`growable`** accessor property of {{jsxref("SharedArrayBuffer")}} instances returns whether this `SharedArrayBuffer` can be grow or not. ## Description The `growable` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the array is constructed. If a `maxByteLength` option was set in the constructor, `growable` will return `true`; if not, it will return `false`. ## Examples ### Using growable In this example, we create a 8-byte buffer that is growable to a max length of 16 bytes, then check its `growable` property, growing it if `growable` returns `true`: ```js const buffer = new SharedArrayBuffer(8, { maxByteLength: 16 }); if (buffer.growable) { console.log("SAB is growable!"); buffer.grow(12); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("SharedArrayBuffer")}} - {{jsxref("SharedArrayBuffer.prototype.grow()")}} - {{jsxref("SharedArrayBuffer.prototype.maxByteLength")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/sharedarraybuffer
data/mdn-content/files/en-us/web/javascript/reference/global_objects/sharedarraybuffer/slice/index.md
--- title: SharedArrayBuffer.prototype.slice() slug: Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/slice page-type: javascript-instance-method browser-compat: javascript.builtins.SharedArrayBuffer.slice --- {{JSRef}} The **`slice()`** method of {{jsxref("SharedArrayBuffer")}} instances returns a new `SharedArrayBuffer` whose contents are a copy of this `SharedArrayBuffer`'s bytes from `start`, inclusive, up to `end`, exclusive. If either `start` or `end` is negative, it refers to an index from the end of the array, as opposed to from the beginning. {{EmbedInteractiveExample("pages/js/sharedarraybuffer-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("SharedArrayBuffer")}} containing the extracted elements. ## Examples ### Using slice() ```js const sab = new SharedArrayBuffer(1024); sab.slice(); // SharedArrayBuffer { byteLength: 1024 } sab.slice(2); // SharedArrayBuffer { byteLength: 1022 } sab.slice(-2); // SharedArrayBuffer { byteLength: 2 } sab.slice(0, 1); // SharedArrayBuffer { byteLength: 1 } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("SharedArrayBuffer")}} - {{jsxref("ArrayBuffer.prototype.slice()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/sharedarraybuffer
data/mdn-content/files/en-us/web/javascript/reference/global_objects/sharedarraybuffer/grow/index.md
--- title: SharedArrayBuffer.prototype.grow() slug: Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/grow page-type: javascript-instance-method browser-compat: javascript.builtins.SharedArrayBuffer.grow --- {{JSRef}} The **`grow()`** method of {{jsxref("SharedArrayBuffer")}} instances grows the `SharedArrayBuffer` to the specified size, in bytes. ## Syntax ```js-nolint grow(newLength) ``` ### Parameters - `newLength` - : The new length, in bytes, to resize the `SharedArrayBuffer` to. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - {{jsxref("TypeError")}} - : Thrown if the `SharedArrayBuffer` is not growable. - {{jsxref("RangeError")}} - : Thrown if `newLength` is larger than the {{jsxref("SharedArrayBuffer/maxByteLength", "maxByteLength")}} of the `SharedArrayBuffer` or smaller than the {{jsxref("SharedArrayBuffer/byteLength", "byteLength")}}. ## Description The `grow()` method grows a `SharedArrayBuffer` to the size specified by the `newLength` parameter, provided that the `SharedArrayBuffer` is [growable](/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/growable) and the new size is less than or equal to the {{jsxref("SharedArrayBuffer/maxByteLength", "maxByteLength")}} of the `SharedArrayBuffer`. New bytes are initialized to 0. ## Examples ### Using grow() In this example, we create a 8-byte buffer that is growable to a max length of 16 bytes, then check its {{jsxref("SharedArrayBuffer/growable", "growable")}} property, growing it if `growable` returns `true`: ```js const buffer = new SharedArrayBuffer(8, { maxByteLength: 16 }); if (buffer.growable) { console.log("SAB is growable!"); buffer.grow(12); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("SharedArrayBuffer")}} - {{jsxref("SharedArrayBuffer.prototype.growable")}} - {{jsxref("SharedArrayBuffer.prototype.maxByteLength")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/sharedarraybuffer
data/mdn-content/files/en-us/web/javascript/reference/global_objects/sharedarraybuffer/bytelength/index.md
--- title: SharedArrayBuffer.prototype.byteLength slug: Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/byteLength page-type: javascript-instance-accessor-property browser-compat: javascript.builtins.SharedArrayBuffer.byteLength --- {{JSRef}} The **`byteLength`** accessor property of {{jsxref("SharedArrayBuffer")}} instances returns the length (in bytes) of this `SharedArrayBuffer`. {{EmbedInteractiveExample("pages/js/sharedarraybuffer-bytelength.html", "shorter")}} ## Description The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the shared array is constructed and cannot be changed. ## Examples ### Using byteLength ```js const sab = new SharedArrayBuffer(1024); sab.byteLength; // 1024 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("SharedArrayBuffer")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/sharedarraybuffer
data/mdn-content/files/en-us/web/javascript/reference/global_objects/sharedarraybuffer/sharedarraybuffer/index.md
--- title: SharedArrayBuffer() constructor slug: Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/SharedArrayBuffer page-type: javascript-constructor browser-compat: javascript.builtins.SharedArrayBuffer.SharedArrayBuffer --- {{JSRef}} > **Note:** The `SharedArrayBuffer` constructor may not always be globally available unless certain [security requirements](/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer#security_requirements) are met. The **`SharedArrayBuffer()`** constructor creates {{jsxref("SharedArrayBuffer")}} objects. {{EmbedInteractiveExample("pages/js/sharedarraybuffer-constructor.html", "shorter")}} ## Syntax ```js-nolint new SharedArrayBuffer(length) new SharedArrayBuffer(length, options) ``` > **Note:** `SharedArrayBuffer()` 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 shared array buffer can be resized to. ### Return value A new `SharedArrayBuffer` object of the specified size, with its {{jsxref("SharedArrayBuffer/maxByteLength", "maxByteLength")}} property set to the specified `maxByteLength` if one was specified. Its contents are initialized to 0. ## Examples ### Always use the new operator to create a SharedArrayBuffer `SharedArrayBuffer` constructors are required to be constructed with a {{jsxref("Operators/new", "new")}} operator. Calling a `SharedArrayBuffer` constructor as a function without `new` will throw a {{jsxref("TypeError")}}. ```js example-bad const sab = SharedArrayBuffer(1024); // TypeError: calling a builtin SharedArrayBuffer constructor // without new is forbidden ``` ```js example-good const sab = new SharedArrayBuffer(1024); ``` ### Growing a growable SharedArrayBuffer In this example, we create an 8-byte buffer that is growable to a max length of 16 bytes, then {{jsxref("SharedArrayBuffer/grow", "grow()")}} it to 12 bytes: ```js const buffer = new SharedArrayBuffer(8, { maxByteLength: 16 }); buffer.grow(12); ``` > **Note:** It is recommended that `maxByteLength` is set to the smallest value possible for your use case. It should never exceed `1073741824` (1GB), to reduce the risk of out-of-memory errors. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Atomics")}} - {{jsxref("ArrayBuffer")}} - [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/sharedarraybuffer
data/mdn-content/files/en-us/web/javascript/reference/global_objects/sharedarraybuffer/maxbytelength/index.md
--- title: SharedArrayBuffer.prototype.maxByteLength slug: Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/maxByteLength page-type: javascript-instance-accessor-property browser-compat: javascript.builtins.SharedArrayBuffer.maxByteLength --- {{JSRef}} The **`maxByteLength`** accessor property of {{jsxref("SharedArrayBuffer")}} instances returns the maximum length (in bytes) that this `SharedArrayBuffer` can be grown to. ## Description The `maxByteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the shared array is constructed, set via the `maxByteLength` option of the {{jsxref("SharedArrayBuffer/SharedArrayBuffer", "SharedArrayBuffer()")}} constructor, and cannot be changed. If this `SharedArrayBuffer` was constructed without specifying a `maxByteLength` value, this property returns a value equal to the value of the `SharedArrayBuffer`'s {{jsxref("SharedArrayBuffer/byteLength", "byteLength")}}. ## Examples ### Using maxByteLength In this example, we create a 8-byte buffer that is resizable to a max length of 16 bytes, then return its `maxByteLength`: ```js const buffer = new SharedArrayBuffer(8, { maxByteLength: 16 }); buffer.maxByteLength; // 16 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("SharedArrayBuffer")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/sharedarraybuffer
data/mdn-content/files/en-us/web/javascript/reference/global_objects/sharedarraybuffer/@@species/index.md
--- title: SharedArrayBuffer[@@species] slug: Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/@@species page-type: javascript-static-accessor-property browser-compat: javascript.builtins.SharedArrayBuffer.@@species --- {{JSRef}} The **`SharedArrayBuffer[@@species]`** static accessor property returns the constructor used to construct return values from `SharedArrayBuffer` methods. > **Warning:** The existence of `@@species` allows execution of arbitrary code and may create security vulnerabilities. It also makes certain optimizations much harder. Engine implementers are [investigating whether to remove this feature](https://github.com/tc39/proposal-rm-builtin-subclassing). Avoid relying on it if possible. ## Syntax ```js-nolint SharedArrayBuffer[Symbol.species] ``` ### Return value The value of the constructor (`this`) on which `get @@species` was called. The return value is used to construct return values from array buffer methods that create new array buffer. ## Description The `@@species` accessor property returns the default constructor for `SharedArrayBuffer` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class SharedArrayBuffer { static get [Symbol.species]() { return this; } } ``` Because of this polymorphic implementation, `@@species` of derived subclasses would also return the constructor itself by default. ```js class SubArrayBuffer extends SharedArrayBuffer {} SubArrayBuffer[Symbol.species] === SharedArrayBuffer; // true ``` When calling array buffer methods that do not mutate the existing array but return a new array buffer instance (for example, [`slice()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/slice)), the array's `constructor[@@species]` will be accessed. The returned constructor will be used to construct the return value of the array buffer method. ## Examples ### Species in ordinary objects The `@@species` property returns the default constructor function, which is the `SharedArrayBuffer` constructor for `SharedArrayBuffer`. ```js SharedArrayBuffer[Symbol.species]; // function SharedArrayBuffer() ``` ### Species in derived objects In an instance of a custom `SharedArrayBuffer` subclass, such as `MySharedArrayBuffer`, the `MySharedArrayBuffer` species is the `MySharedArrayBuffer` constructor. However, you might want to overwrite this, in order to return parent `SharedArrayBuffer` objects in your derived class methods: ```js class MySharedArrayBuffer extends SharedArrayBuffer { // Overwrite MySharedArrayBuffer species to the parent SharedArrayBuffer constructor static get [Symbol.species]() { return SharedArrayBuffer; } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("SharedArrayBuffer")}} - {{jsxref("Symbol.species")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise/index.md
--- title: Promise slug: Web/JavaScript/Reference/Global_Objects/Promise page-type: javascript-class browser-compat: javascript.builtins.Promise --- {{JSRef}} The **`Promise`** object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. To learn about the way promises work and how you can use them, we advise you to read [Using promises](/en-US/docs/Web/JavaScript/Guide/Using_promises) first. ## Description A **`Promise`** is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a _promise_ to supply the value at some point in the future. A `Promise` is in one of these states: - _pending_: initial state, neither fulfilled nor rejected. - _fulfilled_: meaning that the operation was completed successfully. - _rejected_: meaning that the operation failed. The _eventual state_ of a pending promise can either be _fulfilled_ with a value or _rejected_ with a reason (error). When either of these options occur, the associated handlers queued up by a promise's `then` method are called. If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached. A promise is said to be _settled_ if it is either fulfilled or rejected, but not pending. ![Flowchart showing how the Promise state transitions between pending, fulfilled, and rejected via then/catch handlers. A pending promise can become either fulfilled or rejected. If fulfilled, the "on fulfillment" handler, or first parameter of the then() method, is executed and carries out further asynchronous actions. If rejected, the error handler, either passed as the second parameter of the then() method or as the sole parameter of the catch() method, gets executed.](promises.png) You will also hear the term _resolved_ used with promises β€” this means that the promise is settled or "locked-in" to match the eventual state of another promise, and further resolving or rejecting it has no effect. The [States and fates](https://github.com/domenic/promises-unwrapping/blob/master/docs/states-and-fates.md) document from the original Promise proposal contains more details about promise terminology. Colloquially, "resolved" promises are often equivalent to "fulfilled" promises, but as illustrated in "States and fates", resolved promises can be pending or rejected as well. For example: ```js new Promise((resolveOuter) => { resolveOuter( new Promise((resolveInner) => { setTimeout(resolveInner, 1000); }), ); }); ``` This promise is already _resolved_ at the time when it's created (because the `resolveOuter` is called synchronously), but it is resolved with another promise, and therefore won't be _fulfilled_ until 1 second later, when the inner promise fulfills. In practice, the "resolution" is often done behind the scenes and not observable, and only its fulfillment or rejection are. > **Note:** Several other languages have mechanisms for lazy evaluation and deferring a computation, which they also call "promises", e.g. Scheme. Promises in JavaScript represent processes that are already happening, which can be chained with callback functions. If you are looking to lazily evaluate an expression, consider using a function with no arguments e.g. `f = () => expression` to create the lazily-evaluated expression, and `f()` to evaluate the expression immediately. ### Chained Promises The methods {{jsxref("Promise.prototype.then()")}}, {{jsxref("Promise.prototype.catch()")}}, and {{jsxref("Promise.prototype.finally()")}} are used to associate further action with a promise that becomes settled. As these methods return promises, they can be chained. The `.then()` method takes up to two arguments; the first argument is a callback function for the fulfilled case of the promise, and the second argument is a callback function for the rejected case. Each `.then()` returns a newly generated promise object, which can optionally be used for chaining; for example: ```js const myPromise = new Promise((resolve, reject) => { setTimeout(() => { resolve("foo"); }, 300); }); myPromise .then(handleFulfilledA, handleRejectedA) .then(handleFulfilledB, handleRejectedB) .then(handleFulfilledC, handleRejectedC); ``` Processing continues to the next link of the chain even when a `.then()` lacks a callback function. Therefore, a chain can safely omit every _rejection_ callback function until the final `.catch()`. Handling a rejected promise in each `.then()` has consequences further down the promise chain. Sometimes there is no choice, because an error must be handled immediately. In such cases we must throw an error of some type to maintain error state down the chain. On the other hand, in the absence of an immediate need, it is simpler to leave out error handling until a final `.catch()` statement. A `.catch()` is really just a `.then()` without a slot for a callback function for the case when the promise is fulfilled. ```js myPromise .then(handleFulfilledA) .then(handleFulfilledB) .then(handleFulfilledC) .catch(handleRejectedAny); ``` Using [arrow functions](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) for the callback functions, implementation of the promise chain might look something like this: ```js myPromise .then((value) => `${value} and bar`) .then((value) => `${value} and bar again`) .then((value) => `${value} and again`) .then((value) => `${value} and again`) .then((value) => { console.log(value); }) .catch((err) => { console.error(err); }); ``` > **Note:** For faster execution, all synchronous actions should preferably be done within one handler, otherwise it would take several ticks to execute all handlers in sequence. The termination condition of a promise determines the "settled" state of the next promise in the chain. A "fulfilled" state indicates a successful completion of the promise, while a "rejected" state indicates a lack of success. The return value of each fulfilled promise in the chain is passed along to the next `.then()`, while the reason for rejection is passed along to the next rejection-handler function in the chain. The promises of a chain are nested in one another, but get popped like the top of a stack. The first promise in the chain is most deeply nested and is the first to pop. ```plain (promise D, (promise C, (promise B, (promise A) ) ) ) ``` When a `nextValue` is a promise, the effect is a dynamic replacement. The `return` causes a promise to be popped, but the `nextValue` promise is pushed into its place. For the nesting shown above, suppose the `.then()` associated with "promise B" returns a `nextValue` of "promise X". The resulting nesting would look like this: ```plain (promise D, (promise C, (promise X) ) ) ``` A promise can participate in more than one nesting. For the following code, the transition of `promiseA` into a "settled" state will cause both instances of `.then()` to be invoked. ```js const promiseA = new Promise(myExecutorFunc); const promiseB = promiseA.then(handleFulfilled1, handleRejected1); const promiseC = promiseA.then(handleFulfilled2, handleRejected2); ``` An action can be assigned to an already "settled" promise. In that case, the action (if appropriate) will be performed at the first asynchronous opportunity. Note that promises are guaranteed to be asynchronous. Therefore, an action for an already "settled" promise will occur only after the stack has cleared and a clock-tick has passed. The effect is much like that of `setTimeout(action, 0)`. ```js const promiseA = new Promise((resolve, reject) => { resolve(777); }); // At this point, "promiseA" is already settled. promiseA.then((val) => console.log("asynchronous logging has val:", val)); console.log("immediate logging"); // produces output in this order: // immediate logging // asynchronous logging has val: 777 ``` ### Thenables The JavaScript ecosystem had made multiple Promise implementations long before it became part of the language. Despite being represented differently internally, at the minimum, all Promise-like objects implement the _Thenable_ interface. A thenable implements the [`.then()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) method, which is called with two callbacks: one for when the promise is fulfilled, one for when it's rejected. Promises are thenables as well. To interoperate with the existing Promise implementations, the language allows using thenables in place of promises. For example, [`Promise.resolve`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve) will not only resolve promises, but also trace thenables. ```js const aThenable = { then(onFulfilled, onRejected) { onFulfilled({ // The thenable is fulfilled with another thenable then(onFulfilled, onRejected) { onFulfilled(42); }, }); }, }; Promise.resolve(aThenable); // A promise fulfilled with 42 ``` ### Promise concurrency The `Promise` class offers four static methods to facilitate async task [concurrency](https://en.wikipedia.org/wiki/Concurrent_computing): - {{jsxref("Promise.all()")}} - : Fulfills when **all** of the promises fulfill; rejects when **any** of the promises rejects. - {{jsxref("Promise.allSettled()")}} - : Fulfills when **all** promises settle. - {{jsxref("Promise.any()")}} - : Fulfills when **any** of the promises fulfills; rejects when **all** of the promises reject. - {{jsxref("Promise.race()")}} - : Settles when **any** of the promises settles. In other words, fulfills when any of the promises fulfills; rejects when any of the promises rejects. All these methods take an [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) of promises ([thenables](#thenables), to be exact) and return a new promise. They all support subclassing, which means they can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise) constructor β€” accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. The subclass must also have a `resolve` static method that can be called like {{jsxref("Promise.resolve()")}} to resolve values to promises. Note that JavaScript is [single-threaded](/en-US/docs/Glossary/Thread) by nature, so at a given instant, only one task will be executing, although control can shift between different promises, making execution of the promises appear concurrent. [Parallel execution](https://en.wikipedia.org/wiki/Parallel_computing) in JavaScript can only be achieved through [worker threads](/en-US/docs/Web/API/Web_Workers_API). ## Constructor - {{jsxref("Promise/Promise", "Promise()")}} - : Creates a new `Promise` object. The constructor is primarily used to wrap functions that do not already support promises. ## Static properties - {{jsxref("Promise/@@species", "Promise[@@species]")}} - : Returns the constructor used to construct return values from promise methods. ## Static methods - {{jsxref("Promise.all()")}} - : Takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input's promises reject, with this first rejection reason. - {{jsxref("Promise.allSettled()")}} - : Takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise. - {{jsxref("Promise.any()")}} - : Takes an iterable of promises as input and returns a single `Promise`. This returned promise fulfills when any of the input's promises fulfill, with this first fulfillment value. It rejects when all of the input's promises reject (including when an empty iterable is passed), with an {{jsxref("AggregateError")}} containing an array of rejection reasons. - {{jsxref("Promise.race()")}} - : Takes an iterable of promises as input and returns a single `Promise`. This returned promise settles with the eventual state of the first promise that settles. - {{jsxref("Promise.reject()")}} - : Returns a new `Promise` object that is rejected with the given reason. - {{jsxref("Promise.resolve()")}} - : Returns a `Promise` object that is resolved with the given value. If the value is a thenable (i.e. has a `then` method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise, the returned promise will be fulfilled with the value. - {{jsxref("Promise.withResolvers()")}} - : Returns an object containing a new `Promise` object and two functions to resolve or reject it, corresponding to the two parameters passed to the executor of the {{jsxref("Promise/Promise", "Promise()")}} constructor. ## Instance properties These properties are defined on `Promise.prototype` and shared by all `Promise` instances. - {{jsxref("Object/constructor", "Promise.prototype.constructor")}} - : The constructor function that created the instance object. For `Promise` instances, the initial value is the {{jsxref("Promise/Promise", "Promise")}} constructor. - `Promise.prototype[@@toStringTag]` - : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"Promise"`. This property is used in {{jsxref("Object.prototype.toString()")}}. ## Instance methods - {{jsxref("Promise.prototype.catch()")}} - : Appends a rejection handler callback to the promise, and returns a new promise resolving to the return value of the callback if it is called, or to its original fulfillment value if the promise is instead fulfilled. - {{jsxref("Promise.prototype.finally()")}} - : Appends a handler to the promise, and returns a new promise that is resolved when the original promise is resolved. The handler is called when the promise is settled, whether fulfilled or rejected. - {{jsxref("Promise.prototype.then()")}} - : Appends fulfillment and rejection handlers to the promise, and returns a new promise resolving to the return value of the called handler, or to its original settled value if the promise was not handled (i.e. if the relevant handler `onFulfilled` or `onRejected` is not a function). ## Examples ### Basic Example ```js const myFirstPromise = new Promise((resolve, reject) => { // We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed. // In this example, we use setTimeout(...) to simulate async code. // In reality, you will probably be using something like XHR or an HTML API. setTimeout(() => { resolve("Success!"); // Yay! Everything went well! }, 250); }); myFirstPromise.then((successMessage) => { // successMessage is whatever we passed in the resolve(...) function above. // It doesn't have to be a string, but if it is only a succeed message, it probably will be. console.log(`Yay! ${successMessage}`); }); ``` ### Example with diverse situations This example shows diverse techniques for using Promise capabilities and diverse situations that can occur. To understand this, start by scrolling to the bottom of the code block, and examine the promise chain. Upon provision of an initial promise, a chain of promises can follow. The chain is composed of `.then()` calls, and typically (but not necessarily) has a single `.catch()` at the end, optionally followed by `.finally()`. In this example, the promise chain is initiated by a custom-written `new Promise()` construct; but in actual practice, promise chains more typically start with an API function (written by someone else) that returns a promise. The example function `tetheredGetNumber()` shows that a promise generator will utilize `reject()` while setting up an asynchronous call, or within the call-back, or both. The function `promiseGetWord()` illustrates how an API function might generate and return a promise in a self-contained manner. Note that the function `troubleWithGetNumber()` ends with a `throw`. That is forced because a promise chain goes through all the `.then()` promises, even after an error, and without the `throw`, the error would seem "fixed". This is a hassle, and for this reason, it is common to omit `onRejected` throughout the chain of `.then()` promises, and just have a single `onRejected` in the final `catch()`. This code can be run under NodeJS. Comprehension is enhanced by seeing the errors actually occur. To force more errors, change the `threshold` values. ```js // To experiment with error handling, "threshold" values cause errors randomly const THRESHOLD_A = 8; // can use zero 0 to guarantee error function tetheredGetNumber(resolve, reject) { setTimeout(() => { const randomInt = Date.now(); const value = randomInt % 10; if (value < THRESHOLD_A) { resolve(value); } else { reject(`Too large: ${value}`); } }, 500); } function determineParity(value) { const isOdd = value % 2 === 1; return { value, isOdd }; } function troubleWithGetNumber(reason) { const err = new Error("Trouble getting number", { cause: reason }); console.error(err); throw err; } function promiseGetWord(parityInfo) { return new Promise((resolve, reject) => { const { value, isOdd } = parityInfo; if (value >= THRESHOLD_A - 1) { reject(`Still too large: ${value}`); } else { parityInfo.wordEvenOdd = isOdd ? "odd" : "even"; resolve(parityInfo); } }); } new Promise(tetheredGetNumber) .then(determineParity, troubleWithGetNumber) .then(promiseGetWord) .then((info) => { console.log(`Got: ${info.value}, ${info.wordEvenOdd}`); return info; }) .catch((reason) => { if (reason.cause) { console.error("Had previously handled error"); } else { console.error(`Trouble with promiseGetWord(): ${reason}`); } }) .finally((info) => console.log("All done")); ``` ### Advanced Example This small example shows the mechanism of a `Promise`. The `testPromise()` method is called each time the {{HTMLElement("button")}} is clicked. It creates a promise that will be fulfilled, using {{domxref("setTimeout()")}}, to the promise count (number starting from 1) every 1-3 seconds, at random. The `Promise()` constructor is used to create the promise. The fulfillment of the promise is logged, via a fulfill callback set using {{jsxref("Promise/then", "p1.then()")}}. A few logs show how the synchronous part of the method is decoupled from the asynchronous completion of the promise. By clicking the button several times in a short amount of time, you'll even see the different promises being fulfilled one after another. #### HTML ```html <button id="make-promise">Make a promise!</button> <div id="log"></div> ``` #### JavaScript ```js "use strict"; let promiseCount = 0; function testPromise() { const thisPromiseCount = ++promiseCount; const log = document.getElementById("log"); // begin log.insertAdjacentHTML("beforeend", `${thisPromiseCount}) Started<br>`); // We make a new promise: we promise a numeric count of this promise, // starting from 1 (after waiting 3s) const p1 = new Promise((resolve, reject) => { // The executor function is called with the ability // to resolve or reject the promise log.insertAdjacentHTML( "beforeend", `${thisPromiseCount}) Promise constructor<br>`, ); // This is only an example to create asynchronism setTimeout( () => { // We fulfill the promise resolve(thisPromiseCount); }, Math.random() * 2000 + 1000, ); }); // We define what to do when the promise is resolved with the then() call, // and what to do when the promise is rejected with the catch() call p1.then((val) => { // Log the fulfillment value log.insertAdjacentHTML("beforeend", `${val}) Promise fulfilled<br>`); }).catch((reason) => { // Log the rejection reason console.log(`Handle rejected promise (${reason}) here.`); }); // end log.insertAdjacentHTML("beforeend", `${thisPromiseCount}) Promise made<br>`); } const btn = document.getElementById("make-promise"); btn.addEventListener("click", testPromise); ``` #### Result {{EmbedLiveSample("Advanced_Example", "500", "200")}} ### Loading an image with XHR Another simple example using `Promise` and {{domxref("XMLHttpRequest")}} to load an image is available at the MDN GitHub [js-examples](https://github.com/mdn/js-examples/tree/main/promises-test) repository. You can also [see it in action](https://mdn.github.io/js-examples/promises-test/). Each step is commented on and allows you to follow the Promise and XHR architecture closely. ### Incumbent settings object tracking A settings object is an [environment](https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object) that provides additional information when JavaScript code is running. This includes the realm and module map, as well as HTML specific information such as the origin. The incumbent settings object is tracked in order to ensure that the browser knows which one to use for a given piece of user code. To better picture this, we can take a closer look at how the realm might be an issue. A **realm** can be roughly thought of as the global object. What is unique about realms is that they hold all of the necessary information to run JavaScript code. This includes objects like [`Array`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) and [`Error`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error). Each settings object has its own "copy" of these and they are not shared. That can cause some unexpected behavior in relation to promises. In order to get around this, we track something called the **incumbent settings object**. This represents information specific to the context of the user code responsible for a certain function call. To illustrate this a bit further we can take a look at how an [`<iframe>`](/en-US/docs/Web/HTML/Element/iframe) embedded in a document communicates with its host. Since all web APIs are aware of the incumbent settings object, the following will work in all browsers: ```html <!doctype html> <iframe></iframe> <!-- we have a realm here --> <script> // we have a realm here as well const bound = frames[0].postMessage.bind(frames[0], "some data", "*"); // bound is a built-in function β€” there is no user // code on the stack, so which realm do we use? setTimeout(bound); // this still works, because we use the youngest // realm (the incumbent) on the stack </script> ``` The same concept applies to promises. If we modify the above example a little bit, we get this: ```html <!doctype html> <iframe></iframe> <!-- we have a realm here --> <script> // we have a realm here as well const bound = frames[0].postMessage.bind(frames[0], "some data", "*"); // bound is a built in function β€” there is no user // code on the stack β€” which realm do we use? Promise.resolve(undefined).then(bound); // this still works, because we use the youngest // realm (the incumbent) on the stack </script> ``` If we change this so that the `<iframe>` in the document is listening to post messages, we can observe the effect of the incumbent settings object: ```html <!-- y.html --> <!doctype html> <iframe src="x.html"></iframe> <script> const bound = frames[0].postMessage.bind(frames[0], "some data", "*"); Promise.resolve(undefined).then(bound); </script> ``` ```html <!-- x.html --> <!doctype html> <script> window.addEventListener( "message", (event) => { document.querySelector("#text").textContent = "hello"; // this code will only run in browsers that track the incumbent settings object console.log(event); }, false, ); </script> ``` In the above example, the inner text of the `<iframe>` will be updated only if the incumbent settings object is tracked. This is because without tracking the incumbent, we may end up using the wrong environment to send the message. > **Note:** Currently, incumbent realm tracking is fully implemented in Firefox, and has partial implementations in Chrome and Safari. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Promise` in `core-js`](https://github.com/zloirock/core-js#ecmascript-promise) - [Using promises](/en-US/docs/Web/JavaScript/Guide/Using_promises) guide - [Promises/A+ specification](https://promisesaplus.com/) - [JavaScript Promises: an introduction](https://web.dev/articles/promises) on web.dev (2013) - [Callbacks, Promises, and Coroutines: Asynchronous Programming Patterns in JavaScript](https://www.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asynchronicity-in-javascript) slide show by Domenic Denicola (2011)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise/catch/index.md
--- title: Promise.prototype.catch() slug: Web/JavaScript/Reference/Global_Objects/Promise/catch page-type: javascript-instance-method browser-compat: javascript.builtins.Promise.catch --- {{JSRef}} The **`catch()`** method of {{jsxref("Promise")}} instances schedules a function to be called when the promise is rejected. It immediately returns an equivalent {{jsxref("Promise")}} object, allowing you to [chain](/en-US/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. It is a shortcut for {{jsxref("Promise/then", "Promise.prototype.then(undefined, onRejected)")}}. {{EmbedInteractiveExample("pages/js/promise-catch.html")}} ## Syntax ```js-nolint promiseInstance.catch(onRejected) ``` ### Parameters - `onRejected` - : A function to asynchronously execute when this promise becomes rejected. Its return value becomes the fulfillment value of the promise returned by `catch()`. The function is called with the following arguments: - `reason` - : The value that the promise was rejected with. ### Return value Returns a new {{jsxref("Promise")}}. This new promise is always pending when returned, regardless of the current promise's status. If `onRejected` is called, the returned promise will resolve based on the return value of this call, or reject with the thrown error from this call. If the current promise fulfills, `onRejected` is not called and the returned promise fulfills to the same value. ## Description The `catch` method is used for error handling in promise composition. Since it returns a {{jsxref("Promise")}}, it [can be chained](/en-US/docs/Web/JavaScript/Guide/Using_promises#chaining_after_a_catch) in the same way as its sister method, {{jsxref("Promise/then", "then()")}}. If a promise becomes rejected, and there are no rejection handlers to call (a handler can be attached through any of {{jsxref("Promise/then", "then()")}}, {{jsxref("Promise/catch", "catch()")}}, or {{jsxref("Promise/finally", "finally()")}}), then the rejection event is surfaced by the host. In the browser, this results in an [`unhandledrejection`](/en-US/docs/Web/API/Window/unhandledrejection_event) event. If a handler is attached to a rejected promise whose rejection has already caused an unhandled rejection event, then another [`rejectionhandled`](/en-US/docs/Web/API/Window/rejectionhandled_event) event is fired. `catch()` internally calls `then()` on the object upon which it was called, passing `undefined` and `onRejected` as arguments. The value of that call is directly returned. This is observable if you wrap the methods. ```js // overriding original Promise.prototype.then/catch just to add some logs ((Promise) => { const originalThen = Promise.prototype.then; const originalCatch = Promise.prototype.catch; Promise.prototype.then = function (...args) { console.log("Called .then on %o with arguments: %o", this, args); return originalThen.apply(this, args); }; Promise.prototype.catch = function (...args) { console.error("Called .catch on %o with arguments: %o", this, args); return originalCatch.apply(this, args); }; })(Promise); // calling catch on an already resolved promise Promise.resolve().catch(function XXX() {}); // Logs: // Called .catch on Promise{} with arguments: Arguments{1} [0: function XXX()] // Called .then on Promise{} with arguments: Arguments{2} [0: undefined, 1: function XXX()] ``` This means that passing `undefined` still causes the returned promise to be rejected, and you have to pass a function to prevent the final promise from being rejected. Because `catch()` just calls `then()`, it supports subclassing. > **Note:** The examples below are throwing instances of [`Error`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error). As with synchronous [`throw`](/en-US/docs/Web/JavaScript/Reference/Statements/throw) statements, this is considered a good practice; otherwise, the part doing the catching would have to perform checks to see if the argument was a string or an error, and you might lose valuable information such as stack traces. ## Examples ### Using and chaining the catch() method ```js const p1 = new Promise((resolve, reject) => { resolve("Success"); }); p1.then((value) => { console.log(value); // "Success!" throw new Error("oh, no!"); }) .catch((e) => { console.error(e.message); // "oh, no!" }) .then( () => console.log("after a catch the chain is restored"), // "after a catch the chain is restored" () => console.log("Not fired due to the catch"), ); // The following behaves the same as above p1.then((value) => { console.log(value); // "Success!" return Promise.reject("oh, no!"); }) .catch((e) => { console.error(e); // "oh, no!" }) .then( () => console.log("after a catch the chain is restored"), // "after a catch the chain is restored" () => console.log("Not fired due to the catch"), ); ``` ### Gotchas when throwing errors Throwing an error will call the `catch()` method most of the time: ```js const p1 = new Promise((resolve, reject) => { throw new Error("Uh-oh!"); }); p1.catch((e) => { console.error(e); // "Uh-oh!" }); ``` Errors thrown inside asynchronous functions will act like uncaught errors: ```js const p2 = new Promise((resolve, reject) => { setTimeout(() => { throw new Error("Uncaught Exception!"); }, 1000); }); p2.catch((e) => { console.error(e); // This is never called }); ``` Errors thrown after `resolve` is called will be silenced: ```js const p3 = new Promise((resolve, reject) => { resolve(); throw new Error("Silenced Exception!"); }); p3.catch((e) => { console.error(e); // This is never called }); ``` ### catch() is not called if the promise is fulfilled ```js // Create a promise which would not call onReject const p1 = Promise.resolve("calling next"); const p2 = p1.catch((reason) => { // This is never called console.error("catch p1!"); console.error(reason); }); p2.then( (value) => { console.log("next promise's onFulfilled"); console.log(value); // calling next }, (reason) => { console.log("next promise's onRejected"); console.log(reason); }, ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Promise")}} - {{jsxref("Promise.prototype.then()")}} - {{jsxref("Promise.prototype.finally()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise/finally/index.md
--- title: Promise.prototype.finally() slug: Web/JavaScript/Reference/Global_Objects/Promise/finally page-type: javascript-instance-method browser-compat: javascript.builtins.Promise.finally --- {{JSRef}} The **`finally()`** method of {{jsxref("Promise")}} instances schedules a function to be called when the promise is settled (either fulfilled or rejected). It immediately returns an equivalent {{jsxref("Promise")}} object, allowing you to [chain](/en-US/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. This lets you avoid duplicating code in both the promise's {{jsxref("Promise/then", "then()")}} and {{jsxref("Promise/catch", "catch()")}} handlers. {{EmbedInteractiveExample("pages/js/promise-finally.html", "taller")}} ## Syntax ```js-nolint promiseInstance.finally(onFinally) ``` ### Parameters - `onFinally` - : A function to asynchronously execute when this promise becomes settled. Its return value is ignored unless the returned value is a rejected promise. The function is called with no arguments. ### Return value Returns an equivalent {{jsxref("Promise")}}. If the handler throws an error or returns a rejected promise, the promise returned by `finally()` will be rejected with that value instead. Otherwise, the return value of the handler does not affect the state of the original promise. ## Description The `finally()` method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome. The `finally()` method is very similar to calling {{jsxref("Promise/then", "then(onFinally, onFinally)")}}. However, there are a couple of differences: - When creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it. - The `onFinally` callback does not receive any argument. This use case is for precisely when you _do not care_ about the rejection reason or the fulfillment value, and so there's no need to provide it. - A `finally()` call is usually transparent and does not change the eventual state of the original promise. So for example: - Unlike `Promise.resolve(2).then(() => 77, () => {})`, which returns a promise eventually fulfilled with the value `77`, `Promise.resolve(2).finally(() => 77)` returns a promise eventually fulfilled with the value `2`. - Similarly, unlike `Promise.reject(3).then(() => {}, () => 88)`, which returns a promise eventually fulfilled with the value `88`, `Promise.reject(3).finally(() => 88)` returns a promise eventually rejected with the reason `3`. > **Note:** A `throw` (or returning a rejected promise) in the `finally` callback still rejects the returned promise. For example, both `Promise.reject(3).finally(() => { throw 99; })` and `Promise.reject(3).finally(() => Promise.reject(99))` reject the returned promise with the reason `99`. Like {{jsxref("Promise/catch", "catch()")}}, `finally()` internally calls the `then` method on the object upon which it was called. If `onFinally` is not a function, `then()` is called with `onFinally` as both arguments β€” which, for {{jsxref("Promise.prototype.then()")}}, means that no useful handler is attached. Otherwise, `then()` is called with two internally created functions, which behave like the following: > **Warning:** This is only for demonstration purposes and is not a polyfill. ```js promise.then( (value) => Promise.resolve(onFinally()).then(() => value), (reason) => Promise.resolve(onFinally()).then(() => { throw reason; }), ); ``` Because `finally()` calls `then()`, it supports subclassing. Moreover, notice the {{jsxref("Promise.resolve()")}} call above β€” in reality, `onFinally()`'s return value is resolved using the same algorithm as `Promise.resolve()`, but the actual constructor used to construct the resolved promise will be the subclass. `finally()` gets this constructor through [`promise.constructor[@@species]`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/@@species). ## Examples ### Using finally() ```js let isLoading = true; fetch(myRequest) .then((response) => { const contentType = response.headers.get("content-type"); if (contentType && contentType.includes("application/json")) { return response.json(); } throw new TypeError("Oops, we haven't got JSON!"); }) .then((json) => { /* process your JSON further */ }) .catch((error) => { console.error(error); // this line can also throw, e.g. when console = {} }) .finally(() => { isLoading = false; }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Promise.prototype.finally` in `core-js`](https://github.com/zloirock/core-js#ecmascript-promise) - {{jsxref("Promise")}} - {{jsxref("Promise.prototype.then()")}} - {{jsxref("Promise.prototype.catch()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise/allsettled/index.md
--- title: Promise.allSettled() slug: Web/JavaScript/Reference/Global_Objects/Promise/allSettled page-type: javascript-static-method browser-compat: javascript.builtins.Promise.allSettled --- {{JSRef}} The **`Promise.allSettled()`** static method takes an iterable of promises as input and returns a single {{jsxref("Promise")}}. This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise. {{EmbedInteractiveExample("pages/js/promise-allsettled.html", "taller")}} ## Syntax ```js-nolint Promise.allSettled(iterable) ``` ### Parameters - `iterable` - : An [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an {{jsxref("Array")}}) of promises. ### Return value A {{jsxref("Promise")}} that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all promises in the given `iterable` have settled (either fulfilled or rejected). The fulfillment value is an array of objects, each describing the outcome of one promise in the `iterable`, in the order of the promises passed, regardless of completion order. Each outcome object has the following properties: - `status` - : A string, either `"fulfilled"` or `"rejected"`, indicating the eventual state of the promise. - `value` - : Only present if `status` is `"fulfilled"`. The value that the promise was fulfilled with. - `reason` - : Only present if `status` is `"rejected"`. The reason that the promise was rejected with. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. ## Description The `Promise.allSettled()` method is one of the [promise concurrency](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. `Promise.allSettled()` is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you'd always like to know the result of each promise. In comparison, the Promise returned by {{jsxref("Promise.all()")}} may be more appropriate if the tasks are dependent on each other, or if you'd like to immediately reject upon any of them rejecting. ## Examples ### Using Promise.allSettled() ```js Promise.allSettled([ Promise.resolve(33), new Promise((resolve) => setTimeout(() => resolve(66), 0)), 99, Promise.reject(new Error("an error")), ]).then((values) => console.log(values)); // [ // { status: 'fulfilled', value: 33 }, // { status: 'fulfilled', value: 66 }, // { status: 'fulfilled', value: 99 }, // { status: 'rejected', reason: Error: an error } // ] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Promise.allSettled` in `core-js`](https://github.com/zloirock/core-js#ecmascript-promise) - [Using promises](/en-US/docs/Web/JavaScript/Guide/Using_promises) guide - [Graceful asynchronous programming with promises](/en-US/docs/Learn/JavaScript/Asynchronous/Promises) - {{jsxref("Promise")}} - {{jsxref("Promise.all()")}} - {{jsxref("Promise.any()")}} - {{jsxref("Promise.race()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise/any/index.md
--- title: Promise.any() slug: Web/JavaScript/Reference/Global_Objects/Promise/any page-type: javascript-static-method browser-compat: javascript.builtins.Promise.any --- {{JSRef}} The **`Promise.any()`** static method takes an iterable of promises as input and returns a single {{jsxref("Promise")}}. This returned promise fulfills when any of the input's promises fulfills, with this first fulfillment value. It rejects when all of the input's promises reject (including when an empty iterable is passed), with an {{jsxref("AggregateError")}} containing an array of rejection reasons. {{EmbedInteractiveExample("pages/js/promise-any.html")}} ## Syntax ```js-nolint Promise.any(iterable) ``` ### Parameters - `iterable` - : An [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an {{jsxref("Array")}}) of promises. ### Return value A {{jsxref("Promise")}} that is: - **Already rejected**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when any of the promises in the given `iterable` fulfills. The fulfillment value is the fulfillment value of the first promise that was fulfilled. - **Asynchronously rejected**, when all of the promises in the given `iterable` reject. The rejection reason is an {{jsxref("AggregateError")}} containing an array of rejection reasons in its `errors` property. The errors are in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) rejected. ## Description The `Promise.any()` method is one of the [promise concurrency](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. This method is useful for returning the first promise that fulfills. It short-circuits after a promise fulfills, so it does not wait for the other promises to complete once it finds one. Unlike {{jsxref("Promise.all()")}}, which returns an _array_ of fulfillment values, we only get one fulfillment value (assuming at least one promise fulfills). This can be beneficial if we need only one promise to fulfill but we do not care which one does. Note another difference: this method rejects upon receiving an _empty iterable_, since, truthfully, the iterable contains no items that fulfill. You may compare `Promise.any()` and `Promise.all()` with {{jsxref("Array.prototype.some()")}} and {{jsxref("Array.prototype.every()")}}. Also, unlike {{jsxref("Promise.race()")}}, which returns the first _settled_ value (either fulfillment or rejection), this method returns the first _fulfilled_ value. This method ignores all rejected promises up until the first promise that fulfills. ## Examples ### Using Promise.any() `Promise.any()` fulfills with the first promise to fulfill, even if a promise rejects first. This is in contrast to {{jsxref("Promise.race()")}}, which fulfills or rejects with the first promise to settle. ```js const pErr = new Promise((resolve, reject) => { reject("Always fails"); }); const pSlow = new Promise((resolve, reject) => { setTimeout(resolve, 500, "Done eventually"); }); const pFast = new Promise((resolve, reject) => { setTimeout(resolve, 100, "Done quick"); }); Promise.any([pErr, pSlow, pFast]).then((value) => { console.log(value); // pFast fulfills first }); // Logs: // Done quick ``` ### Rejections with AggregateError `Promise.any()` rejects with an {{jsxref("AggregateError")}} if no promise fulfills. ```js const failure = new Promise((resolve, reject) => { reject("Always fails"); }); Promise.any([failure]).catch((err) => { console.log(err); }); // AggregateError: No Promise in Promise.any was resolved ``` ### Displaying the first image loaded In this example, we have a function that fetches an image and returns a blob. We use `Promise.any()` to fetch a couple of images and display the first one available (i.e. whose promise has resolved). ```js async function fetchAndDecode(url, description) { const res = await fetch(url); if (!res.ok) { throw new Error(`HTTP error! status: ${res.status}`); } const data = await res.blob(); return [data, description]; } const coffee = fetchAndDecode("coffee.jpg", "Coffee"); const tea = fetchAndDecode("tea.jpg", "Tea"); Promise.any([coffee, tea]) .then(([blob, description]) => { const objectURL = URL.createObjectURL(blob); const image = document.createElement("img"); image.src = objectURL; image.alt = description; document.body.appendChild(image); }) .catch((e) => { console.error(e); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Promise.any` in `core-js`](https://github.com/zloirock/core-js#ecmascript-promise) - {{jsxref("Promise")}} - {{jsxref("Promise.all()")}} - {{jsxref("Promise.allSettled()")}} - {{jsxref("Promise.race()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise/race/index.md
--- title: Promise.race() slug: Web/JavaScript/Reference/Global_Objects/Promise/race page-type: javascript-static-method browser-compat: javascript.builtins.Promise.race --- {{JSRef}} The **`Promise.race()`** static method takes an iterable of promises as input and returns a single {{jsxref("Promise")}}. This returned promise settles with the eventual state of the first promise that settles. {{EmbedInteractiveExample("pages/js/promise-race.html", "taller")}} ## Syntax ```js-nolint Promise.race(iterable) ``` ### Parameters - `iterable` - : An [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an {{jsxref("Array")}}) of promises. ### Return value A {{jsxref("Promise")}} that **asynchronously settles** with the eventual state of the first promise in the `iterable` to settle. In other words, it fulfills if the first promise to settle is fulfilled, and rejects if the first promise to settle is rejected. The returned promise remains pending forever if the `iterable` passed is empty. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) settled. ## Description The `Promise.race()` method is one of the [promise concurrency](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It's useful when you want the first async task to complete, but do not care about its eventual state (i.e. it can either succeed or fail). If the iterable contains one or more non-promise values and/or an already settled promise, then `Promise.race()` will settle to the first of these values found in the iterable. ## Examples ### Using Promise.race() This example shows how `Promise.race()` can be used to race several timers implemented with [`setTimeout()`](/en-US/docs/Web/API/setTimeout). The timer with the shortest time always wins the race and becomes the resulting promise's state. ```js function sleep(time, value, state) { return new Promise((resolve, reject) => { setTimeout(() => { if (state === "fulfill") { return resolve(value); } else { return reject(new Error(value)); } }, time); }); } const p1 = sleep(500, "one", "fulfill"); const p2 = sleep(100, "two", "fulfill"); Promise.race([p1, p2]).then((value) => { console.log(value); // "two" // Both fulfill, but p2 is faster }); const p3 = sleep(100, "three", "fulfill"); const p4 = sleep(500, "four", "reject"); Promise.race([p3, p4]).then( (value) => { console.log(value); // "three" // p3 is faster, so it fulfills }, (error) => { // Not called }, ); const p5 = sleep(500, "five", "fulfill"); const p6 = sleep(100, "six", "reject"); Promise.race([p5, p6]).then( (value) => { // Not called }, (error) => { console.error(error.message); // "six" // p6 is faster, so it rejects }, ); ``` ### Asynchronicity of Promise.race This following example demonstrates the asynchronicity of `Promise.race`. Unlike other promise concurrency methods, `Promise.race` is always asynchronous: it never settles synchronously, even when the `iterable` is empty. ```js // Passing an array of promises that are already resolved, // to trigger Promise.race as soon as possible const resolvedPromisesArray = [Promise.resolve(33), Promise.resolve(44)]; const p = Promise.race(resolvedPromisesArray); // Immediately logging the value of p console.log(p); // Using setTimeout, we can execute code after the stack is empty setTimeout(() => { console.log("the stack is now empty"); console.log(p); }); // Logs, in order: // Promise { <state>: "pending" } // the stack is now empty // Promise { <state>: "fulfilled", <value>: 33 } ``` An empty iterable causes the returned promise to be forever pending: ```js const foreverPendingPromise = Promise.race([]); console.log(foreverPendingPromise); setTimeout(() => { console.log("the stack is now empty"); console.log(foreverPendingPromise); }); // Logs, in order: // Promise { <state>: "pending" } // the stack is now empty // Promise { <state>: "pending" } ``` If the iterable contains one or more non-promise value and/or an already settled promise, then `Promise.race` will settle to the first of these values found in the array: ```js const foreverPendingPromise = Promise.race([]); const alreadyFulfilledProm = Promise.resolve(100); const arr = [foreverPendingPromise, alreadyFulfilledProm, "non-Promise value"]; const arr2 = [foreverPendingPromise, "non-Promise value", Promise.resolve(100)]; const p = Promise.race(arr); const p2 = Promise.race(arr2); console.log(p); console.log(p2); setTimeout(() => { console.log("the stack is now empty"); console.log(p); console.log(p2); }); // Logs, in order: // Promise { <state>: "pending" } // Promise { <state>: "pending" } // the stack is now empty // Promise { <state>: "fulfilled", <value>: 100 } // Promise { <state>: "fulfilled", <value>: "non-Promise value" } ``` ### Using Promise.race() to implement request timeout You can race a potentially long-lasting request with a timer that rejects, so that when the time limit has elapsed, the resulting promise automatically rejects. ```js const data = Promise.race([ fetch("/api"), new Promise((resolve, reject) => { // Reject after 5 seconds setTimeout(() => reject(new Error("Request timed out")), 5000); }), ]) .then((res) => res.json()) .catch((err) => displayError(err)); ``` If the `data` promise fulfills, it will contain the data fetched from `/api`; otherwise, it will reject if `fetch` remains pending for 5 seconds and loses the race with the `setTimeout` timer. ### Using Promise.race() to detect the status of a promise Because `Promise.race()` resolves to the first non-pending promise in the iterable, we can check a promise's state, including if it's pending. This example is adapted from [`promise-status-async`](https://github.com/kudla/promise-status-async/blob/master/lib/promiseState.js). ```js function promiseState(promise) { const pendingState = { status: "pending" }; return Promise.race([promise, pendingState]).then( (value) => value === pendingState ? value : { status: "fulfilled", value }, (reason) => ({ status: "rejected", reason }), ); } ``` In this function, if `promise` is pending, the second value, `pendingState`, which is a non-promise, becomes the result of the race; otherwise, if `promise` is already settled, we may know its state through the `onFulfilled` and `onRejected` handlers. For example: ```js const p1 = new Promise((res) => setTimeout(() => res(100), 100)); const p2 = new Promise((res) => setTimeout(() => res(200), 200)); const p3 = new Promise((res, rej) => setTimeout(() => rej(300), 100)); async function getStates() { console.log(await promiseState(p1)); console.log(await promiseState(p2)); console.log(await promiseState(p3)); } console.log("Immediately after initiation:"); getStates(); setTimeout(() => { console.log("After waiting for 100ms:"); getStates(); }, 100); // Logs: // Immediately after initiation: // { status: 'pending' } // { status: 'pending' } // { status: 'pending' } // After waiting for 100ms: // { status: 'fulfilled', value: 100 } // { status: 'pending' } // { status: 'rejected', reason: 300 } ``` > **Note:** The `promiseState` function still runs asynchronously, because there is no way to synchronously get a promise's value (i.e. without `then()` or `await`), even when it is already settled. However, `promiseState()` always fulfills within one tick and never actually waits for any promise's settlement. ### Comparison with Promise.any() `Promise.race` takes the first settled {{jsxref("Promise")}}. ```js const promise1 = new Promise((resolve, reject) => { setTimeout(resolve, 500, "one"); }); const promise2 = new Promise((resolve, reject) => { setTimeout(reject, 100, "two"); }); Promise.race([promise1, promise2]) .then((value) => { console.log("succeeded with value:", value); }) .catch((reason) => { // Only promise1 is fulfilled, but promise2 is faster console.error("failed with reason:", reason); }); // failed with reason: two ``` {{jsxref("Promise.any")}} takes the first fulfilled {{jsxref("Promise")}}. ```js const promise1 = new Promise((resolve, reject) => { setTimeout(resolve, 500, "one"); }); const promise2 = new Promise((resolve, reject) => { setTimeout(reject, 100, "two"); }); Promise.any([promise1, promise2]) .then((value) => { // Only promise1 is fulfilled, even though promise2 settled sooner console.log("succeeded with value:", value); }) .catch((reason) => { console.error("failed with reason:", reason); }); // succeeded with value: one ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Promise")}} - {{jsxref("Promise.all()")}} - {{jsxref("Promise.allSettled()")}} - {{jsxref("Promise.any()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise/withresolvers/index.md
--- title: Promise.withResolvers() slug: Web/JavaScript/Reference/Global_Objects/Promise/withResolvers page-type: javascript-static-method browser-compat: javascript.builtins.Promise.withResolvers --- {{JSRef}} The **`Promise.withResolvers()`** static method returns an object containing a new {{jsxref("Promise")}} object and two functions to resolve or reject it, corresponding to the two parameters passed to the executor of the {{jsxref("Promise/Promise", "Promise()")}} constructor. ## Syntax ```js-nolint Promise.withResolvers() ``` ### Parameters None. ### Return value A plain object containing the following properties: - `promise` - : A {{jsxref("Promise")}} object. - `resolve` - : A function that resolves the promise. For its semantics, see the {{jsxref("Promise/Promise", "Promise()")}} constructor reference. - `reject` - : A function that rejects the promise. For its semantics, see the {{jsxref("Promise/Promise", "Promise()")}} constructor reference. ## Description `Promise.withResolvers()` is exactly equivalent to the following code: ```js let resolve, reject; const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); ``` Except that it is more concise and does not require the use of {{jsxref("Statements/let", "let")}}. The key difference when using `Promise.withResolvers()` is that the resolution and rejection functions now live in the same scope as the promise itself, instead of being created and used once within the executor. This may enable some more advanced use cases, such as when reusing them for recurring events, particularly with streams and queues. This also generally results in less nesting than wrapping a lot of logic within the executor. `Promise.withResolvers()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will contain a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise) constructor β€” accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. ## Examples ### Transforming a stream to an async iterable The use case of `Promise.withResolvers()` is when you have a promise that should be resolved or rejected by some event listener that cannot be wrapped inside the promise executor. The following example transforms a Node.js [readable stream](https://nodejs.org/api/stream.html#class-streamreadable) to an [async iterable](/en-US/docs/Web/JavaScript/Reference/Statements/async_function*). Each `promise` here represents a single batch of data available, and each time the current batch is read, a new promise is created for the next batch. Note how the event listeners are only attached once, but actually call a different version of the `resolve` and `reject` functions each time. ```js async function* readableToAsyncIterable(stream) { let { promise, resolve, reject } = Promise.withResolvers(); stream.on("error", (error) => reject(error)); stream.on("end", () => resolve()); stream.on("readable", () => resolve()); while (stream.readable) { await promise; let chunk; while ((chunk = stream.read())) { yield chunk; } ({ promise, resolve, reject } = Promise.withResolvers()); } } ``` ### Calling withResolvers() on a non-Promise constructor `Promise.withResolvers()` is a generic method. It can be called on any constructor that implements the same signature as the `Promise()` constructor. For example, we can call it on a constructor that passes `console.log` as the `resolve` and `reject` functions to `executor`: ```js class NotPromise { constructor(executor) { // The "resolve" and "reject" functions behave nothing like the native // promise's, but Promise.withResolvers() just returns them, as is. executor( (value) => console.log("Resolved", value), (reason) => console.log("Rejected", reason), ); } } const { promise, resolve, reject } = Promise.withResolvers.call(NotPromise); resolve("hello"); // Logs: Resolved hello ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Promise.withResolvers` in `core-js`](https://github.com/zloirock/core-js#promisewithresolvers) - [Using promises](/en-US/docs/Web/JavaScript/Guide/Using_promises) guide - {{jsxref("Promise")}} - [`Promise()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise)
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise/resolve/index.md
--- title: Promise.resolve() slug: Web/JavaScript/Reference/Global_Objects/Promise/resolve page-type: javascript-static-method browser-compat: javascript.builtins.Promise.resolve --- {{JSRef}} The **`Promise.resolve()`** static method "resolves" a given value to a {{jsxref("Promise")}}. If the value is a promise, that promise is returned; if the value is a [thenable](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables), `Promise.resolve()` will call the `then()` method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value. This function flattens nested layers of promise-like objects (e.g. a promise that fulfills to a promise that fulfills to something) into a single layer β€” a promise that fulfills to a non-thenable value. {{EmbedInteractiveExample("pages/js/promise-resolve.html")}} ## Syntax ```js-nolint Promise.resolve(value) ``` ### Parameters - `value` - : Argument to be resolved by this `Promise`. Can also be a `Promise` or a thenable to resolve. ### Return value A {{jsxref("Promise")}} that is resolved with the given value, or the promise passed as value, if the value was a promise object. A resolved promise can be in any of the states β€” fulfilled, rejected, or pending. For example, resolving a rejected promise will still result in a rejected promise. ## Description `Promise.resolve()` _resolves_ a promise, which is not the same as fulfilling or rejecting the promise. See [Promise description](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for definitions of the terminology. In brief, `Promise.resolve()` returns a promise whose eventual state depends on another promise, thenable object, or other value. `Promise.resolve()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise) constructor β€” accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.resolve()` special-cases native `Promise` instances. If `value` belongs to `Promise` or a subclass, and `value.constructor === Promise`, then `value` is directly returned by `Promise.resolve()`, without creating a new `Promise` instance. Otherwise, `Promise.resolve()` is essentially a shorthand for `new Promise((resolve) => resolve(value))`. The bulk of the resolving logic is actually implemented by [the `resolve` function](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolve_function) passed by the `Promise()` constructor. In summary: - If a non-[thenable](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value is passed, the returned promise is already fulfilled with that value. - If a thenable is passed, the returned promise will adopt the state of that thenable by calling the `then` method and passing a pair of resolving functions as arguments. (But because native promises directly pass through `Promise.resolve()` without creating a wrapper, the `then` method is not called on native promises.) If the `resolve` function receives another thenable object, it will be resolved again, so that the eventual fulfillment value of the promise will never be thenable. ## Examples ### Using the static Promise.resolve method ```js Promise.resolve("Success").then( (value) => { console.log(value); // "Success" }, (reason) => { // not called }, ); ``` ### Resolving an array ```js const p = Promise.resolve([1, 2, 3]); p.then((v) => { console.log(v[0]); // 1 }); ``` ### Resolving another Promise `Promise.resolve()` reuses existing `Promise` instances. If it's resolving a native promise, it returns the same promise instance without creating a wrapper. ```js const original = Promise.resolve(33); const cast = Promise.resolve(original); cast.then((value) => { console.log(`value: ${value}`); }); console.log(`original === cast ? ${original === cast}`); // Logs, in order: // original === cast ? true // value: 33 ``` The inverted order of the logs is due to the fact that the `then` handlers are called asynchronously. See the {{jsxref("Promise/then", "then()")}} reference for more information. ### Resolving thenables and throwing Errors ```js // Resolving a thenable object const p1 = Promise.resolve({ then(onFulfill, onReject) { onFulfill("fulfilled!"); }, }); console.log(p1 instanceof Promise); // true, object casted to a Promise p1.then( (v) => { console.log(v); // "fulfilled!" }, (e) => { // not called }, ); // Thenable throws // Promise rejects const p2 = Promise.resolve({ then() { throw new TypeError("Throwing"); }, }); p2.then( (v) => { // not called }, (e) => { console.error(e); // TypeError: Throwing }, ); // Thenable throws after callback // Promise resolves const p3 = Promise.resolve({ then(onFulfilled) { onFulfilled("Resolving"); throw new TypeError("Throwing"); }, }); p3.then( (v) => { console.log(v); // "Resolving" }, (e) => { // not called }, ); ``` Nested thenables will be "deeply flattened" to a single promise. ```js const thenable = { then(onFulfilled, onRejected) { onFulfilled({ // The thenable is fulfilled with another thenable then(onFulfilled, onRejected) { onFulfilled(42); }, }); }, }; Promise.resolve(thenable).then((v) => { console.log(v); // 42 }); ``` > **Warning:** Do not call `Promise.resolve()` on a thenable that resolves to itself. That leads to infinite recursion, because it attempts to flatten an infinitely-nested promise. ```js example-bad const thenable = { then(onFulfilled, onRejected) { onFulfilled(thenable); }, }; Promise.resolve(thenable); // Will lead to infinite recursion. ``` ### Calling resolve() on a non-Promise constructor `Promise.resolve()` is a generic method. It can be called on any constructor that implements the same signature as the `Promise()` constructor. For example, we can call it on a constructor that passes it `console.log` as `resolve`: ```js class NotPromise { constructor(executor) { // The "resolve" and "reject" functions behave nothing like the // native promise's, but Promise.resolve() calls them in the same way. executor( (value) => console.log("Resolved", value), (reason) => console.log("Rejected", reason), ); } } Promise.resolve.call(NotPromise, "foo"); // Logs "Resolved foo" ``` The ability to flatten nested thenables is implemented by the `resolve` function of the `Promise()` constructor, so if you call it on another constructor, nested thenables may not be flattened, depending on how that constructor implements its `resolve` function. ```js const thenable = { then(onFulfilled, onRejected) { onFulfilled({ // The thenable is fulfilled with another thenable then(onFulfilled, onRejected) { onFulfilled(42); }, }); }, }; Promise.resolve.call(NotPromise, thenable); // Logs "Resolved { then: [Function: then] }" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Promise")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise/promise/index.md
--- title: Promise() constructor slug: Web/JavaScript/Reference/Global_Objects/Promise/Promise page-type: javascript-constructor browser-compat: javascript.builtins.Promise.Promise --- {{JSRef}} The **`Promise()`** constructor creates {{jsxref("Promise")}} objects. It is primarily used to wrap callback-based APIs that do not already support promises. {{EmbedInteractiveExample("pages/js/promise-constructor.html", "taller")}} ## Syntax ```js-nolint new Promise(executor) ``` > **Note:** `Promise()` 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 - `executor` - : A {{jsxref("function")}} to be executed by the constructor. It receives two functions as parameters: `resolveFunc` and `rejectFunc`. Any errors thrown in the `executor` will cause the promise to be rejected, and the return value will be neglected. The semantics of `executor` are detailed below. ### Return value When called via `new`, the `Promise` constructor returns a promise object. The promise object will become _resolved_ when either of the functions `resolveFunc` or `rejectFunc` are invoked. Note that if you call `resolveFunc` or `rejectFunc` and pass another `Promise` object as an argument, it can be said to be "resolved", but still not "settled". See the [Promise description](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#description) for more explanation. ## Description Traditionally (before promises), asynchronous tasks were designed as callbacks. ```js readFile("./data.txt", (error, result) => { // This callback will be called when the task is done, with the // final `error` or `result`. Any operation dependent on the // result must be defined within this callback. }); // Code here is immediately executed after the `readFile` request // is fired. It does not wait for the callback to be called, hence // making `readFile` "asynchronous". ``` To take advantage of the readability improvement and language features offered by promises, the `Promise()` constructor allows one to transform the callback-based API to a promise-based one. > **Note:** If your task is already promise-based, you likely do not need the `Promise()` constructor. The `executor` is custom code that ties an outcome in a callback to a promise. You, the programmer, write the `executor`. Its signature is expected to be: ```js function executor(resolveFunc, rejectFunc) { // Typically, some asynchronous operation that accepts a callback, // like the `readFile` function above } ``` `resolveFunc` and `rejectFunc` are also functions, and you can give them whatever actual names you want. Their signatures are simple: they accept a single parameter of any type. ```js resolveFunc(value); // call on resolved rejectFunc(reason); // call on rejected ``` The `value` parameter passed to `resolveFunc` can be another promise object, in which case the newly constructed promise's state will be "locked in" to the promise passed (as part of the [resolution](#the_resolve_function) promise). The `rejectFunc` has semantics close to the [`throw`](/en-US/docs/Web/JavaScript/Reference/Statements/throw) statement, so `reason` is typically an [`Error`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) instance. If either `value` or `reason` is omitted, the promise is fulfilled/rejected with `undefined`. The `executor`'s completion state has limited effect on the promise's state: - The `executor` return value is ignored. `return` statements within the `executor` merely impact control flow and alter whether a part of the function is executed, but do not have any impact on the promise's fulfillment value. If `executor` exits and it's impossible for `resolveFunc` or `rejectFunc` to be called in the future (for example, there are no async tasks scheduled), then the promise remains pending forever. - If an error is thrown in the `executor`, the promise is rejected, unless `resolveFunc` or `rejectFunc` has already been called. > **Note:** The existence of pending promises does not prevent the program from exiting. If the event loop is empty, the program exits despite any pending promises (because those are necessarily forever-pending). Here's a summary of the typical flow: 1. At the time when the constructor generates the new `Promise` object, it also generates a corresponding pair of functions for `resolveFunc` and `rejectFunc`; these are "tethered" to the `Promise` object. 2. `executor` typically wraps some asynchronous operation which provides a callback-based API. The callback (the one passed to the original callback-based API) is defined within the `executor` code, so it has access to the `resolveFunc` and `rejectFunc`. 3. The `executor` is called synchronously (as soon as the `Promise` is constructed) with the `resolveFunc` and `rejectFunc` functions as arguments. 4. The code within the `executor` has the opportunity to perform some operation. The eventual completion of the asynchronous task is communicated with the promise instance via the side effect caused by `resolveFunc` or `rejectFunc`. The side effect is that the `Promise` object becomes "resolved". - If `resolveFunc` is called first, the value passed will be [resolved](#the_resolve_function). The promise may stay pending (in case another [thenable](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) is passed), become fulfilled (in most cases where a non-thenable value is passed), or become rejected (in case of an invalid resolution value). - If `rejectFunc` is called first, the promise instantly becomes rejected. - Once one of the resolving functions (`resolveFunc` or `rejectFunc`) is called, the promise stays resolved. Only the first call to `resolveFunc` or `rejectFunc` affects the promise's eventual state, and subsequent calls to either function can neither change the fulfillment value/rejection reason nor toggle its eventual state from "fulfilled" to "rejected" or opposite. - If `executor` exits by throwing an error, then the promise is rejected. However, the error is ignored if one of the resolving functions has already been called (so that the promise is already resolved). - Resolving the promise does not necessarily cause the promise to become fulfilled or rejected (i.e. settled). The promise may still be pending because it's resolved with another thenable, but its eventual state will match that of the resolved thenable. 5. Once the promise settles, it (asynchronously) invokes any further handlers associated through {{jsxref("Promise/then", "then()")}}, {{jsxref("Promise/catch", "catch()")}}, or {{jsxref("Promise/finally", "finally()")}}. The eventual fulfillment value or rejection reason is passed to the invocation of fulfillment and rejection handlers as an input parameter (see [Chained Promises](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#chained_promises)). For example, the callback-based `readFile` API above can be transformed into a promise-based one. ```js const readFilePromise = (path) => new Promise((resolve, reject) => { readFile(path, (error, result) => { if (error) { reject(error); } else { resolve(result); } }); }); readFilePromise("./data.txt") .then((result) => console.log(result)) .catch((error) => console.error("Failed to read data")); ``` The `resolve` and `reject` callbacks are only available within the scope of the executor function, which means you can't access them after the promise is constructed. If you want to construct the promise before deciding how to resolve it, you can use the {{jsxref("Promise.withResolvers()")}} method instead, which exposes the `resolve` and `reject` functions. ### The resolve function The `resolve` function has the following behaviors: - If it's called with the same value as the newly created promise (the promise it's "tethered to"), the promise is rejected with a {{jsxref("TypeError")}}. - If it's called with a non-[thenable](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) value (a primitive, or an object whose `then` property is not callable, including when the property is not present), the promise is immediately fulfilled with that value. - If it's called with a thenable value (including another `Promise` instance), then the thenable's `then` method is saved and called in the future (it's always called asynchronously). The `then` method will be called with two callbacks, which are two new functions with the exact same behaviors as the `resolveFunc` and `rejectFunc` passed to the `executor` function. If calling the `then` method throws, then the current promise is rejected with the thrown error. In the last case, it means code like: ```js new Promise((resolve, reject) => { resolve(thenable); }); ``` Is roughly equivalent to: ```js new Promise((resolve, reject) => { try { thenable.then( (value) => resolve(value), (reason) => reject(reason), ); } catch (e) { reject(e); } }); ``` Except that in the `resolve(thenable)` case: 1. `resolve` is called synchronously, so that calling `resolve` or `reject` again has no effect, even when the handlers attached through `anotherPromise.then()` are not called yet. 2. The `then` method is called asynchronously, so that the promise will never be instantly resolved if a thenable is passed. Because `resolve` is called again with whatever `thenable.then()` passes to it as `value`, the resolver function is able to flatten nested thenables, where a thenable calls its `onFulfilled` handler with another thenable. The effect is that the fulfillment handler of a real promise will never receive a thenable as its fulfillment value. ## Examples ### Turning a callback-based API into a promise-based one To provide a function with promise functionality, have it return a promise by calling the `resolve` and `reject` functions at the correct times. ```js function myAsyncFunction(url) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open("GET", url); xhr.onload = () => resolve(xhr.responseText); xhr.onerror = () => reject(xhr.statusText); xhr.send(); }); } ``` ### Effect of calling resolveFunc Calling `resolveFunc` causes the promise to become resolved, so that calling `resolveFunc` or `rejectFunc` again has no effect. However, the promise may be in any of the states: pending, fulfilled, or rejected. This `pendingResolved` promise is resolved the time it's created, because it has already been "locked in" to match the eventual state of the inner promise, and calling `resolveOuter` or `rejectOuter` or throwing an error later in the executor has no effect on its eventual state. However, the inner promise is still pending until 100ms later, so the outer promise is also pending: ```js const pendingResolved = new Promise((resolveOuter, rejectOuter) => { resolveOuter( new Promise((resolveInner) => { setTimeout(() => { resolveInner("inner"); }, 100); }), ); }); ``` This `fulfilledResolved` promise becomes fulfilled the moment it's resolved, because it's resolved with a non-thenable value. However, when it's created, it's unresolved, because neither `resolve` nor `reject` has been called yet. An unresolved promise is necessarily pending: ```js const fulfilledResolved = new Promise((resolve, reject) => { setTimeout(() => { resolve("outer"); }, 100); }); ``` Calling `rejectFunc` obviously causes the promise to reject. However, there are also two ways to cause the promise to instantly become rejected even when the `resolveFunc` callback is called. ```js // 1. Resolving with the promise itself const rejectedResolved1 = new Promise((resolve) => { // Note: resolve has to be called asynchronously, // so that the rejectedResolved1 variable is initialized setTimeout(() => resolve(rejectedResolved1)); // TypeError: Chaining cycle detected for promise #<Promise> }); // 2. Resolving with an object which throws when accessing the `then` property const rejectedResolved2 = new Promise((resolve) => { resolve({ get then() { throw new Error("Can't get then property"); }, }); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Promise` in `core-js`](https://github.com/zloirock/core-js#ecmascript-promise) - [Using promises](/en-US/docs/Web/JavaScript/Guide/Using_promises) guide - {{jsxref("Promise.withResolvers()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise/all/index.md
--- title: Promise.all() slug: Web/JavaScript/Reference/Global_Objects/Promise/all page-type: javascript-static-method browser-compat: javascript.builtins.Promise.all --- {{JSRef}} The **`Promise.all()`** static method takes an iterable of promises as input and returns a single {{jsxref("Promise")}}. This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passed), with an array of the fulfillment values. It rejects when any of the input's promises rejects, with this first rejection reason. {{EmbedInteractiveExample("pages/js/promise-all.html")}} ## Syntax ```js-nolint Promise.all(iterable) ``` ### Parameters - `iterable` - : An [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) (such as an {{jsxref("Array")}}) of promises. ### Return value A {{jsxref("Promise")}} that is: - **Already fulfilled**, if the `iterable` passed is empty. - **Asynchronously fulfilled**, when all the promises in the given `iterable` fulfill. The fulfillment value is an array of fulfillment values, in the order of the promises passed, regardless of completion order. If the `iterable` passed is non-empty but contains no pending promises, the returned promise is still asynchronously (instead of synchronously) fulfilled. - **Asynchronously rejected**, when any of the promises in the given `iterable` rejects. The rejection reason is the rejection reason of the first promise that was rejected. ## Description The `Promise.all()` method is one of the [promise concurrency](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) methods. It can be useful for aggregating the results of multiple promises. It is typically used when there are multiple related asynchronous tasks that the overall code relies on to work successfully β€” all of whom we want to fulfill before the code execution continues. `Promise.all()` will reject immediately upon **any** of the input promises rejecting. In comparison, the promise returned by {{jsxref("Promise.allSettled()")}} will wait for all input promises to complete, regardless of whether or not one rejects. Use `allSettled()` if you need the final result of every promise in the input iterable. ## Examples ### Using Promise.all() `Promise.all` waits for all fulfillments (or the first rejection). ```js const p1 = Promise.resolve(3); const p2 = 1337; const p3 = new Promise((resolve, reject) => { setTimeout(() => { resolve("foo"); }, 100); }); Promise.all([p1, p2, p3]).then((values) => { console.log(values); // [3, 1337, "foo"] }); ``` If the `iterable` contains non-promise values, they will be ignored, but still counted in the returned promise array value (if the promise is fulfilled): ```js // All values are non-promises, so the returned promise gets fulfilled const p = Promise.all([1, 2, 3]); // The only input promise is already fulfilled, // so the returned promise gets fulfilled const p2 = Promise.all([1, 2, 3, Promise.resolve(444)]); // One (and the only) input promise is rejected, // so the returned promise gets rejected const p3 = Promise.all([1, 2, 3, Promise.reject(555)]); // Using setTimeout, we can execute code after the queue is empty setTimeout(() => { console.log(p); console.log(p2); console.log(p3); }); // Logs: // Promise { <state>: "fulfilled", <value>: Array[3] } // Promise { <state>: "fulfilled", <value>: Array[4] } // Promise { <state>: "rejected", <reason>: 555 } ``` ### Asynchronicity or synchronicity of Promise.all This following example demonstrates the asynchronicity of `Promise.all` when a non-empty `iterable` is passed: ```js // Passing an array of promises that are already resolved, // to trigger Promise.all as soon as possible const resolvedPromisesArray = [Promise.resolve(33), Promise.resolve(44)]; const p = Promise.all(resolvedPromisesArray); // Immediately logging the value of p console.log(p); // Using setTimeout, we can execute code after the queue is empty setTimeout(() => { console.log("the queue is now empty"); console.log(p); }); // Logs, in order: // Promise { <state>: "pending" } // the queue is now empty // Promise { <state>: "fulfilled", <value>: Array[2] } ``` The same thing happens if `Promise.all` rejects: ```js const mixedPromisesArray = [Promise.resolve(33), Promise.reject(44)]; const p = Promise.all(mixedPromisesArray); console.log(p); setTimeout(() => { console.log("the queue is now empty"); console.log(p); }); // Logs: // Promise { <state>: "pending" } // the queue is now empty // Promise { <state>: "rejected", <reason>: 44 } ``` `Promise.all` resolves synchronously if and only if the `iterable` passed is empty: ```js const p = Promise.all([]); // Will be immediately resolved const p2 = Promise.all([1337, "hi"]); // Non-promise values are ignored, but the evaluation is done asynchronously console.log(p); console.log(p2); setTimeout(() => { console.log("the queue is now empty"); console.log(p2); }); // Logs: // Promise { <state>: "fulfilled", <value>: Array[0] } // Promise { <state>: "pending" } // the queue is now empty // Promise { <state>: "fulfilled", <value>: Array[2] } ``` ### Using Promise.all() with async functions Within [async functions](/en-US/docs/Web/JavaScript/Reference/Statements/async_function), it's very common to "over-await" your code. For example, given the following functions: ```js function promptForDishChoice() { return new Promise((resolve, reject) => { const dialog = document.createElement("dialog"); dialog.innerHTML = ` <form method="dialog"> <p>What would you like to eat?</p> <select> <option value="pizza">Pizza</option> <option value="pasta">Pasta</option> <option value="salad">Salad</option> </select> <menu> <li><button value="cancel">Cancel</button></li> <li><button type="submit" value="ok">OK</button></li> </menu> </form> `; dialog.addEventListener("close", () => { if (dialog.returnValue === "ok") { resolve(dialog.querySelector("select").value); } else { reject(new Error("User cancelled dialog")); } }); document.body.appendChild(dialog); dialog.showModal(); }); } async function fetchPrices() { const response = await fetch("/prices"); return await response.json(); } ``` You may write a function like this: ```js example-bad async function getPrice() { const choice = await promptForDishChoice(); const prices = await fetchPrices(); return prices[choice]; } ``` However, note that the execution of `promptForDishChoice` and `fetchPrices` don't depend on the result of each other. While the user is choosing their dish, it's fine for the prices to be fetched in the background, but in the code above, the [`await`](/en-US/docs/Web/JavaScript/Reference/Operators/await) operator causes the async function to pause until the choice is made, and then again until the prices are fetched. We can use `Promise.all` to run them concurrently, so that the user doesn't have to wait for the prices to be fetched before the result is given: ```js example-good async function getPrice() { const [choice, prices] = await Promise.all([ promptForDishChoice(), fetchPrices(), ]); return prices[choice]; } ``` `Promise.all` is the best choice of [concurrency method](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#promise_concurrency) here, because error handling is intuitive β€” if any of the promises reject, the result is no longer available, so the whole `await` expression throws. `Promise.all` accepts an iterable of promises, so if you are using it to run several async functions concurrently, you need to call the async functions and use the returned promises. Directly passing the functions to `Promise.all` does not work, since they are not promises. ```js example-bad async function getPrice() { const [choice, prices] = await Promise.all([ promptForDishChoice, fetchPrices, ]); // `choice` and `prices` are still the original async functions; // Promise.all() does nothing to non-promises } ``` ### Promise.all fail-fast behavior `Promise.all` is rejected if any of the elements are rejected. For example, if you pass in four promises that resolve after a timeout and one promise that rejects immediately, then `Promise.all` will reject immediately. ```js const p1 = new Promise((resolve, reject) => { setTimeout(() => resolve("one"), 1000); }); const p2 = new Promise((resolve, reject) => { setTimeout(() => resolve("two"), 2000); }); const p3 = new Promise((resolve, reject) => { setTimeout(() => resolve("three"), 3000); }); const p4 = new Promise((resolve, reject) => { setTimeout(() => resolve("four"), 4000); }); const p5 = new Promise((resolve, reject) => { reject(new Error("reject")); }); // Using .catch: Promise.all([p1, p2, p3, p4, p5]) .then((values) => { console.log(values); }) .catch((error) => { console.error(error.message); }); // Logs: // "reject" ``` It is possible to change this behavior by handling possible rejections: ```js const p1 = new Promise((resolve, reject) => { setTimeout(() => resolve("p1_delayed_resolution"), 1000); }); const p2 = new Promise((resolve, reject) => { reject(new Error("p2_immediate_rejection")); }); Promise.all([p1.catch((error) => error), p2.catch((error) => error)]).then( (values) => { console.log(values[0]); // "p1_delayed_resolution" console.error(values[1]); // "Error: p2_immediate_rejection" }, ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Promise")}} - {{jsxref("Promise.allSettled()")}} - {{jsxref("Promise.any()")}} - {{jsxref("Promise.race()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise/reject/index.md
--- title: Promise.reject() slug: Web/JavaScript/Reference/Global_Objects/Promise/reject page-type: javascript-static-method browser-compat: javascript.builtins.Promise.reject --- {{JSRef}} The **`Promise.reject()`** static method returns a `Promise` object that is rejected with a given reason. {{EmbedInteractiveExample("pages/js/promise-reject.html")}} ## Syntax ```js-nolint Promise.reject(reason) ``` ### Parameters - `reason` - : Reason why this `Promise` rejected. ### Return value A {{jsxref("Promise")}} that is rejected with the given reason. ## Description The static `Promise.reject` function returns a `Promise` that is rejected. For debugging purposes and selective error catching, it is useful to make `reason` an `instanceof` {{jsxref("Error")}}. `Promise.reject()` is generic and supports subclassing, which means it can be called on subclasses of `Promise`, and the result will be a promise of the subclass type. To do so, the subclass's constructor must implement the same signature as the [`Promise()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise) constructor β€” accepting a single `executor` function that can be called with the `resolve` and `reject` callbacks as parameters. `Promise.reject()` is essentially a shorthand for `new Promise((resolve, reject) => reject(reason))`. Unlike {{jsxref("Promise.resolve()")}}, `Promise.reject()` always wraps `reason` in a new `Promise` object, even when `reason` is already a `Promise`. ## Examples ### Using the static Promise.reject() method ```js Promise.reject(new Error("fail")).then( () => { // not called }, (error) => { console.error(error); // Stacktrace }, ); ``` ### Rejecting with a promise Unlike {{jsxref("Promise.resolve")}}, the `Promise.reject` method does not reuse existing `Promise` instances. It always returns a new `Promise` instance that wraps `reason`. ```js const p = Promise.resolve(1); const rejected = Promise.reject(p); console.log(rejected === p); // false rejected.catch((v) => { console.log(v === p); // true }); ``` ### Calling reject() on a non-Promise constructor `Promise.reject()` is a generic method. It can be called on any constructor that implements the same signature as the `Promise()` constructor. For example, we can call it on a constructor that passes it `console.log` as `reject`: ```js class NotPromise { constructor(executor) { // The "resolve" and "reject" functions behave nothing like the // native promise's, but Promise.reject() calls them in the same way. executor( (value) => console.log("Resolved", value), (reason) => console.log("Rejected", reason), ); } } Promise.reject.call(NotPromise, "foo"); // Logs "Rejected foo" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Promise")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise/then/index.md
--- title: Promise.prototype.then() slug: Web/JavaScript/Reference/Global_Objects/Promise/then page-type: javascript-instance-method browser-compat: javascript.builtins.Promise.then --- {{JSRef}} The **`then()`** method of {{jsxref("Promise")}} instances takes up to two arguments: callback functions for the fulfilled and rejected cases of the `Promise`. It immediately returns an equivalent {{jsxref("Promise")}} object, allowing you to [chain](/en-US/docs/Web/JavaScript/Guide/Using_promises#chaining) calls to other promise methods. {{EmbedInteractiveExample("pages/js/promise-then.html")}} ## Syntax ```js-nolint then(onFulfilled) then(onFulfilled, onRejected) ``` ### Parameters - `onFulfilled` - : A function to asynchronously execute when this promise becomes fulfilled. Its return value becomes the fulfillment value of the promise returned by `then()`. The function is called with the following arguments: - `value` - : The value that the promise was fulfilled with. If it is not a function, it is internally replaced with an _identity_ function (`(x) => x`) which simply passes the fulfillment value forward. - `onRejected` {{optional_inline}} - : A function to asynchronously execute when this promise becomes rejected. Its return value becomes the fulfillment value of the promise returned by `then()`. The function is called with the following arguments: - `reason` - : The value that the promise was rejected with. If it is not a function, it is internally replaced with a _thrower_ function (`(x) => { throw x; }`) which throws the rejection reason it received. ### Return value Returns a new {{jsxref("Promise")}} immediately. This new promise is always pending when returned, regardless of the current promise's status. One of the `onFulfilled` and `onRejected` handlers will be executed to handle the current promise's fulfillment or rejection. The call always happens asynchronously, even when the current promise is already settled. The behavior of the returned promise (call it `p`) depends on the handler's execution result, following a specific set of rules. If the handler function: - returns a value: `p` gets fulfilled with the returned value as its value. - doesn't return anything: `p` gets fulfilled with `undefined` as its value. - throws an error: `p` gets rejected with the thrown error as its value. - returns an already fulfilled promise: `p` gets fulfilled with that promise's value as its value. - returns an already rejected promise: `p` gets rejected with that promise's value as its value. - returns another pending promise: `p` is pending and becomes fulfilled/rejected with that promise's value as its value immediately after that promise becomes fulfilled/rejected. ## Description The `then()` method schedules callback functions for the eventual completion of a Promise β€” either fulfillment or rejection. It is the primitive method of promises: the [thenable](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) protocol expects all promise-like objects to expose a `then()` method, and the {{jsxref("Promise/catch", "catch()")}} and {{jsxref("Promise/finally", "finally()")}} methods both work by invoking the object's `then()` method. For more information about the `onRejected` handler, see the {{jsxref("Promise/catch", "catch()")}} reference. `then()` returns a new promise object. If you call the `then()` method twice on the same promise object (instead of chaining), then this promise object will have two pairs of settlement handlers. All handlers attached to the same promise object are always called in the order they were added. Moreover, the two promises returned by each call of `then()` start separate chains and do not wait for each other's settlement. [Thenable](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) objects that arise along the `then()` chain are always [resolved](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise#the_resolve_function) β€” the `onFulfilled` handler never receives a thenable object, and any thenable returned by either handler are always resolved before being passed to the next handler. This is because when constructing the new promise, the `resolve` and `reject` functions passed by the `executor` are saved, and when the current promise settles, the respective function will be called with the fulfillment value or rejection reason. The resolving logic comes from the `resolve` function passed by the {{jsxref("Promise/Promise", "Promise()")}} constructor. `then()` supports subclassing, which means it can be called on instances of subclasses of `Promise`, and the result will be a promise of the subclass type. You can customize the type of the return value through the [`@@species`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/@@species) property. ## Examples ### Using the then() method ```js const p1 = new Promise((resolve, reject) => { resolve("Success!"); // or // reject(new Error("Error!")); }); p1.then( (value) => { console.log(value); // Success! }, (reason) => { console.error(reason); // Error! }, ); ``` ### Having a non-function as either parameter ```js Promise.resolve(1).then(2).then(console.log); // 1 Promise.reject(1).then(2, 2).then(console.log, console.log); // 1 ``` ### Chaining The `then` method returns a new `Promise`, which allows for method chaining. If the function passed as handler to `then` returns a `Promise`, an equivalent `Promise` will be exposed to the subsequent `then` in the method chain. The below snippet simulates asynchronous code with the `setTimeout` function. ```js Promise.resolve("foo") // 1. Receive "foo", concatenate "bar" to it, and resolve that to the next then .then( (string) => new Promise((resolve, reject) => { setTimeout(() => { string += "bar"; resolve(string); }, 1); }), ) // 2. receive "foobar", register a callback function to work on that string // and print it to the console, but not before returning the unworked on // string to the next then .then((string) => { setTimeout(() => { string += "baz"; console.log(string); // foobarbaz }, 1); return string; }) // 3. print helpful messages about how the code in this section will be run // before the string is actually processed by the mocked asynchronous code in the // previous then block. .then((string) => { console.log( "Last Then: oops... didn't bother to instantiate and return a promise in the prior then so the sequence may be a bit surprising", ); // Note that `string` will not have the 'baz' bit of it at this point. This // is because we mocked that to happen asynchronously with a setTimeout function console.log(string); // foobar }); // Logs, in order: // Last Then: oops... didn't bother to instantiate and return a promise in the prior then so the sequence may be a bit surprising // foobar // foobarbaz ``` The value returned from `then()` is resolved in the same way as {{jsxref("Promise.resolve()")}}. This means [thenable objects](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables) are supported, and if the return value is not a promise, it's implicitly wrapped in a `Promise` and then resolved. ```js const p2 = new Promise((resolve, reject) => { resolve(1); }); p2.then((value) => { console.log(value); // 1 return value + 1; }).then((value) => { console.log(value, "- A synchronous value works"); // 2 - A synchronous value works }); p2.then((value) => { console.log(value); // 1 }); ``` A `then` call returns a promise that eventually rejects if the function throws an error or returns a rejected Promise. ```js Promise.resolve() .then(() => { // Makes .then() return a rejected promise throw new Error("Oh no!"); }) .then( () => { console.log("Not called."); }, (error) => { console.error(`onRejected function called: ${error.message}`); }, ); ``` In practice, it is often desirable to [`catch()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch) rejected promises rather than `then()`'s two-case syntax, as demonstrated below. ```js Promise.resolve() .then(() => { // Makes .then() return a rejected promise throw new Error("Oh no!"); }) .catch((error) => { console.error(`onRejected function called: ${error.message}`); }) .then(() => { console.log("I am always called even if the prior then's promise rejects"); }); ``` In all other cases, the returned promise eventually fulfills. In the following example, the first `then()` returns `42` wrapped in a fulfilled Promise, even though the previous Promise in the chain was rejected. ```js Promise.reject() .then( () => 99, () => 42, ) // onRejected returns 42 which is wrapped in a fulfilled Promise .then((solution) => console.log(`Resolved with ${solution}`)); // Fulfilled with 42 ``` If `onFulfilled` returns a promise, the return value of `then` will be fulfilled/rejected based on the eventual state of that promise. ```js function resolveLater(resolve, reject) { setTimeout(() => { resolve(10); }, 1000); } function rejectLater(resolve, reject) { setTimeout(() => { reject(new Error("Error")); }, 1000); } const p1 = Promise.resolve("foo"); const p2 = p1.then(() => { // Return promise here, that will be resolved to 10 after 1 second return new Promise(resolveLater); }); p2.then( (v) => { console.log("resolved", v); // "resolved", 10 }, (e) => { // not called console.error("rejected", e); }, ); const p3 = p1.then(() => { // Return promise here, that will be rejected with 'Error' after 1 second return new Promise(rejectLater); }); p3.then( (v) => { // not called console.log("resolved", v); }, (e) => { console.error("rejected", e); // "rejected", 'Error' }, ); ``` You can use chaining to implement one function with a Promise-based API on top of another such function. ```js function fetchCurrentData() { // The fetch() API returns a Promise. This function // exposes a similar API, except the fulfillment // value of this function's Promise has had more // work done on it. return fetch("current-data.json").then((response) => { if (response.headers.get("content-type") !== "application/json") { throw new TypeError(); } const j = response.json(); // maybe do something with j // fulfillment value given to user of // fetchCurrentData().then() return j; }); } ``` ### Asynchronicity of then() The following is an example to demonstrate the asynchronicity of the `then` method. ```js // Using a resolved promise 'resolvedProm' for example, // the function call 'resolvedProm.then(...)' returns a new promise immediately, // but its handler '(value) => {...}' will get called asynchronously as demonstrated by the console.logs. // the new promise is assigned to 'thenProm', // and thenProm will be resolved with the value returned by handler const resolvedProm = Promise.resolve(33); console.log(resolvedProm); const thenProm = resolvedProm.then((value) => { console.log( `this gets called after the end of the main stack. the value received is: ${value}, the value returned is: ${ value + 1 }`, ); return value + 1; }); console.log(thenProm); // Using setTimeout, we can postpone the execution of a function to the moment the stack is empty setTimeout(() => { console.log(thenProm); }); // Logs, in order: // Promise {[[PromiseStatus]]: "resolved", [[PromiseResult]]: 33} // Promise {[[PromiseStatus]]: "pending", [[PromiseResult]]: undefined} // "this gets called after the end of the main stack. the value received is: 33, the value returned is: 34" // Promise {[[PromiseStatus]]: "resolved", [[PromiseResult]]: 34} ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Promise")}} - {{jsxref("Promise.prototype.catch()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise
data/mdn-content/files/en-us/web/javascript/reference/global_objects/promise/@@species/index.md
--- title: Promise[@@species] slug: Web/JavaScript/Reference/Global_Objects/Promise/@@species page-type: javascript-static-accessor-property browser-compat: javascript.builtins.Promise.@@species --- {{JSRef}} The **`Promise[@@species]`** static accessor property returns the constructor used to construct return values from promise 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 Promise[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 promise chaining methods that create new promises. ## Description The `@@species` accessor property returns the default constructor for `Promise` objects. Subclass constructors may override it to change the constructor assignment. The default implementation is basically: ```js // Hypothetical underlying implementation for illustration class Promise { 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 SubPromise extends Promise {} SubPromise[Symbol.species] === SubPromise; // true ``` Promise chaining methods β€” [`then()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then), [`catch()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch), and [`finally()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally) β€” return new promise objects. They get the constructor to construct the new promise through `this.constructor[@@species]`. If `this.constructor` is `undefined`, or if `this.constructor[@@species]` is `undefined` or `null`, the default {{jsxref("Promise/Promise", "Promise()")}} constructor is used. Otherwise, the constructor returned by `this.constructor[@@species]` is used to construct the new promise object. ## Examples ### Species in ordinary objects The `Symbol.species` property returns the default constructor function, which is the `Promise` constructor for `Promise`. ```js Promise[Symbol.species]; // [Function: Promise] ``` ### Species in derived objects In an instance of a custom `Promise` subclass, such as `MyPromise`, the `MyPromise` species is the `MyPromise` constructor. However, you might want to override this, in order to return parent `Promise` objects in your derived class methods. ```js class MyPromise extends Promise { // Override MyPromise species to the parent Promise constructor static get [Symbol.species]() { return Promise; } } ``` By default, promise methods would return promises with the type of the subclass. ```js class MyPromise extends Promise { someValue = 1; } console.log(MyPromise.resolve(1).then(() => {}).someValue); // 1 ``` By overriding `@@species`, the promise methods will return the base `Promise` type. ```js class MyPromise extends Promise { someValue = 1; static get [Symbol.species]() { return Promise; } } console.log(MyPromise.resolve(1).then(() => {}).someValue); // undefined ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("Promise")}} - {{jsxref("Symbol.species")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/decodeuri/index.md
--- title: decodeURI() slug: Web/JavaScript/Reference/Global_Objects/decodeURI page-type: javascript-function browser-compat: javascript.builtins.decodeURI --- {{jsSidebar("Objects")}} The **`decodeURI()`** function decodes a Uniform Resource Identifier (URI) previously created by {{jsxref("encodeURI()")}} or a similar routine. {{EmbedInteractiveExample("pages/js/globalprops-decodeuri.html")}} ## Syntax ```js-nolint decodeURI(encodedURI) ``` ### Parameters - `encodedURI` - : A complete, encoded Uniform Resource Identifier. ### Return value A new string representing the unencoded version of the given encoded Uniform Resource Identifier (URI). ### Exceptions - {{jsxref("URIError")}} - : Thrown if `encodedURI` contains a `%` not followed by two hexadecimal digits, or if the escape sequence does not encode a valid UTF-8 character. ## Description `decodeURI()` is a function property of the global object. The `decodeURI()` function decodes the URI by treating each escape sequence in the form `%XX` as one UTF-8 code unit (one byte). In UTF-8, the number of leading 1 bits in the first byte, which may be 0 (for 1-byte {{Glossary("ASCII")}} characters), 2, 3, or 4, indicates the number of bytes in the character. So by reading the first escape sequence, `decodeURI()` can determine how many more escape sequences to consume. If `decodeURI()` fails to find the expected number of sequences, or if the escape sequences don't encode a valid UTF-8 character, a {{jsxref("URIError")}} is thrown. `decodeURI()` decodes all escape sequences, but if the escape sequence encodes one of the following characters, the escape sequence is preserved in the output string (because they are part of the URI syntax): ```plain ; / ? : @ & = + $ , # ``` ## Examples ### Decoding a Cyrillic URL ```js decodeURI( "https://developer.mozilla.org/ru/docs/JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B", ); // "https://developer.mozilla.org/ru/docs/JavaScript_ΡˆΠ΅Π»Π»Ρ‹" ``` ### decodeURI() vs. decodeURIComponent() `decodeURI()` assumes the input is a full URI, so it does not decode characters that are part of the URI syntax. ```js decodeURI( "https://developer.mozilla.org/docs/JavaScript%3A%20a_scripting_language", ); // "https://developer.mozilla.org/docs/JavaScript%3A a_scripting_language" decodeURIComponent( "https://developer.mozilla.org/docs/JavaScript%3A%20a_scripting_language", ); // "https://developer.mozilla.org/docs/JavaScript: a_scripting_language" ``` ### Catching errors ```js try { const a = decodeURI("%E0%A4%A"); } catch (e) { console.error(e); } // URIError: malformed URI sequence ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{jsxref("decodeURIComponent()")}} - {{jsxref("encodeURI()")}} - {{jsxref("encodeURIComponent()")}}
0
data/mdn-content/files/en-us/web/javascript/reference/global_objects
data/mdn-content/files/en-us/web/javascript/reference/global_objects/int32array/index.md
--- title: Int32Array slug: Web/JavaScript/Reference/Global_Objects/Int32Array page-type: javascript-class browser-compat: javascript.builtins.Int32Array --- {{JSRef}} The **`Int32Array`** typed array represents an array of 32-bit signed 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). `Int32Array` is a subclass of the hidden {{jsxref("TypedArray")}} class. ## Constructor - {{jsxref("Int32Array/Int32Array", "Int32Array()")}} - : Creates a new `Int32Array` object. ## Static properties _Also inherits static properties from its parent {{jsxref("TypedArray")}}_. - {{jsxref("TypedArray/BYTES_PER_ELEMENT", "Int32Array.BYTES_PER_ELEMENT")}} - : Returns a number value of the element size. `4` in the case of `Int32Array`. ## 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 `Int32Array.prototype` and shared by all `Int32Array` instances. - {{jsxref("TypedArray/BYTES_PER_ELEMENT", "Int32Array.prototype.BYTES_PER_ELEMENT")}} - : Returns a number value of the element size. `4` in the case of a `Int32Array`. - {{jsxref("Object/constructor", "Int32Array.prototype.constructor")}} - : The constructor function that created the instance object. For `Int32Array` instances, the initial value is the {{jsxref("Int32Array/Int32Array", "Int32Array")}} constructor. ## Instance methods _Inherits instance methods from its parent {{jsxref("TypedArray")}}_. ## Examples ### Different ways to create an Int32Array ```js // From a length const int32 = new Int32Array(2); int32[0] = 42; console.log(int32[0]); // 42 console.log(int32.length); // 2 console.log(int32.BYTES_PER_ELEMENT); // 4 // From an array const x = new Int32Array([21, 31]); console.log(x[1]); // 31 // From another TypedArray const y = new Int32Array(x); console.log(y[0]); // 21 // From an ArrayBuffer const buffer = new ArrayBuffer(32); const z = new Int32Array(buffer, 4, 4); console.log(z.byteOffset); // 4 // From an iterable const iterable = (function* () { yield* [1, 2, 3]; })(); const int32FromIterable = new Int32Array(iterable); console.log(int32FromIterable); // Int32Array [1, 2, 3] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `Int32Array` 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