Map() constructor - JavaScript

Map() constructor
=================

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

Syntax
------

```js
new Map()
new Map(iterable)
```

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

### Parameters

`iterable` Optional

 An `Array` or other
 iterable object
 whose elements are key-value pairs. (For example, arrays with two elements,
 such as `[[ 1, 'one' ],[ 2, 'two' ]]`.) Each key-value pair is added to the
 new `Map`.

Examples
--------

### Creating a new Map

```js
const myMap = new Map([
  [1, "one"],
  [2, "two"],
  [3, "three"],
]);
```

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

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

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

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

See also
--------

* Polyfill for `Map` in `core-js`
* `Set`
* `WeakMap`
* `WeakSet`


Map.prototype.set() - JavaScript

Map.prototype.set()
===================

The **`set()`** method of `Map` instances adds or updates an entry in this map with a specified key and a value.

Try it
------

Syntax
------

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

### Parameters

`key`

The key of the element to add to the `Map` object. The key may be any JavaScript type (any primitive value or any type of JavaScript object).

`value`

The value of the element to add to the `Map` object. The value may be any JavaScript type (any primitive value or any type of JavaScript object).

### Return value

The `Map` object.

Examples
--------

### Using set()

```js
const myMap = new Map();

// Add new elements to the map
myMap.set("bar", "foo");
myMap.set(1, "foobar");

// Update an element in the map
myMap.set("bar", "baz");
```

### Using the set() with chaining

 Since the `set()` method returns back the same `Map` object, you can chain the
 method call like below:

```js
// Add new elements to the map with chaining.
myMap.set("bar", "foo").set(1, "foobar").set(2, "baz");
```

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

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

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

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

See also
--------

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


Map.prototype.size - JavaScript

Map.prototype.size
==================

The **`size`** accessor property of `Map` instances returns the number of elements in this map.

Try it
------

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

 The value of `size` is an integer representing how many entries the `Map` object
 has. A set accessor function for `size` is `undefined`; you can not change this
 property.

Examples
--------

### Using size

```js
const myMap = new Map();
myMap.set("a", "alpha");
myMap.set("b", "beta");
myMap.set("g", "gamma");

console.log(myMap.size); // 3
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-map.prototype.size |

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

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

See also
--------

* `Map`


Map.prototype.values() - JavaScript

Map.prototype.values()
======================

The **`values()`** method of `Map` instances returns a new *map iterator* object that contains the values for each element in this map in insertion order.

Try it
------

Syntax
------

```js
values()
```

### Parameters

None.

### Return value

A new iterable iterator object.

Examples
--------

### Using values()

```js
const myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");

const mapIter = myMap.values();

console.log(mapIter.next().value); // "foo"
console.log(mapIter.next().value); // "bar"
console.log(mapIter.next().value); // "baz"
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-map.prototype.values |

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

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

See also
--------

* `Map.prototype.entries()`
* `Map.prototype.keys()`


Map.groupBy() - JavaScript

Map.groupBy()
=============

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback

**Note:** In some versions of some browsers, this method was implemented as the method `Array.prototype.groupToMap()`. Due to web compatibility issues, it is now implemented as a static method. Check the browser compatibility table for details.

The **`Map.groupBy()`** static method groups the elements of a given iterable using the values returned by a provided callback function. The final returned `Map` uses the unique values from the test function as keys, which can be used to get the array of elements in each group.

The method is primarily useful when grouping elements that are associated with an object, and in particular when that object might change over time. If the object is invariant, you might instead represent it using a string, and group elements with `Object.groupBy()`.

Try it
------

Syntax
------

```js
Map.groupBy(items, callbackFn)
```

### Parameters

`items`

An iterable (such as an `Array`) whose elements will be grouped.

`callbackFn`

A function to execute for each element in the iterable. It should return a value (object or primitive) indicating the group of the current element. The function is called with the following arguments:

`element`

The current element being processed.

`index`

The index of the current element being processed.

### Return value

A `Map` object with keys for each group, each assigned to an array containing the elements of the associated group.

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

`Map.groupBy()` calls a provided `callbackFn` function once for each element in an iterable. The callback function should return a value indicating the group of the associated element. The values returned by `callbackFn` are used as keys for the `Map` returned by `Map.groupBy()`. Each key has an associated array containing all the elements for which the callback returned the same value.

The elements in the returned `Map` and the original iterable are the same (not deep copies). Changing the internal structure of the elements will be reflected in both the original iterable and the returned `Map`.

This method is useful when you need to group information that is related to a particular object that might potentially change over time. This is because even if the object is modified, it will continue to work as a key to the returned `Map`. If you instead create a string representation for the object and use that as a grouping key in `Object.groupBy()`, you must maintain the mapping between the original object and its representation as the object changes.

**Note:** To access the groups in the returned `Map`, you must use the same object that was originally used as a key in the `Map` (although you may modify its properties). You can't use another object that just happens to have the same name and properties.

`Map.groupBy` does not read the value of `this`. It can be called on any object and a new `Map` instance will be returned.

Examples
--------

### Using Map.groupBy()

First we define an array containing objects representing an inventory of different foodstuffs. Each food has a `type` and a `quantity`.

```js
const inventory = [
  { name: "asparagus", type: "vegetables", quantity: 9 },
  { name: "bananas", type: "fruit", quantity: 5 },
  { name: "goat", type: "meat", quantity: 23 },
  { name: "cherries", type: "fruit", quantity: 12 },
  { name: "fish", type: "meat", quantity: 22 },
];
```

The code below uses `Map.groupBy()` with an arrow function that returns the object keys named `restock` or `sufficient`, depending on whether the element has `quantity < 6`. The returned `result` object is a `Map` so we need to call `get()` with the key to obtain the array.

```js
const restock = { restock: true };
const sufficient = { restock: false };
const result = Map.groupBy(inventory, ({ quantity }) =>
  quantity < 6 ? restock : sufficient,
);
console.log(result.get(restock));
// [{ name: "bananas", type: "fruit", quantity: 5 }]
```

Note that the function argument `{ quantity }` is a basic example of object destructuring syntax for function arguments. This unpacks the `quantity` property of an object passed as a parameter, and assigns it to a variable named `quantity` in the body of the function. This is a very succinct way to access the relevant values of elements within a function.

The key to a `Map` can be modified and still used. However you can't recreate the key and still use it. For this reason it is important that anything that needs to use the map keeps a reference to its keys.

```js
// The key can be modified and still used
restock["fast"] = true;
console.log(result.get(restock));
// [{ name: "bananas", type: "fruit", quantity: 5 }]

// A new key can't be used, even if it has the same structure!
const restock2 = { restock: true };
console.log(result.get(restock2)); // undefined
```

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

| Specification |
| --- |
| Array Grouping # sec-map.groupby |

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

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

See also
--------

* Polyfill of `Map.groupBy` in `core-js`
* Indexed collections guide
* `Array.prototype.reduce()`
* `Map()`
* `Object.groupBy()`


Map.prototype.forEach() - JavaScript

Map.prototype.forEach()
=======================

 The **`forEach()`** method of `Map` instances executes a provided function once per each key/value
 pair in this map, in insertion order.

Try it
------

Syntax
------

```js
forEach(callbackFn)
forEach(callbackFn, thisArg)
```

### Parameters

`callbackFn`

A function to execute for each entry in the map. The function is called with the following arguments:

`value`

Value of each iteration.

`key`

Key of each iteration.

`map`

The map being iterated.

`thisArg` Optional

A value to use as `this` when executing `callbackFn`.

### Return value

None (`undefined`).

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

 The `forEach` method executes the provided `callback` once for each key of the
 map which actually exist. It is not invoked for keys which have been deleted.
 However, it is executed for values which are present but have the value
 `undefined`.

`callback` is invoked with **three arguments**:

* the entry's `value`
* the entry's `key`
* the **`Map` object** being traversed

 If a `thisArg` parameter is provided to `forEach`, it will be passed to
 `callback` when invoked, for use as its `this` value. Otherwise, the value
 `undefined` will be passed for use as its `this` value. The `this` value
 ultimately observable by `callback` is determined according to
 the usual rules for determining the `this` seen by a function.

 Each value is visited once, except in the case when it was deleted and re-added
 before `forEach` has finished. `callback` is not invoked for values deleted
 before being visited. New values added before `forEach` has finished will be
 visited.

Examples
--------

### Printing the contents of a Map object

The following code logs a line for each element in an `Map` object:

```js
function logMapElements(value, key, map) {
  console.log(`map.get('${key}') = ${value}`);
}
new Map([
  ["foo", 3],
  ["bar", {}],
  ["baz", undefined],
]).forEach(logMapElements);
// Logs:
// "map.get('foo') = 3"
// "map.get('bar') = [object Object]"
// "map.get('baz') = undefined"
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-map.prototype.foreach |

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

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

See also
--------

* `Array.prototype.forEach()`
* `Set.prototype.forEach()`


Map.prototype.has() - JavaScript

Map.prototype.has()
===================

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

Try it
------

Syntax
------

```js
has(key)
```

### Parameters

`key`

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

### Return value

`true` if an element with the specified key exists in the `Map` object;
 otherwise `false`.

Examples
--------

### Using has()

```js
const myMap = new Map();
myMap.set("bar", "foo");

console.log(myMap.has("bar")); // true
console.log(myMap.has("baz")); // false
```

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

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

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

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

See also
--------

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


Map.prototype.get() - JavaScript

Map.prototype.get()
===================

 The **`get()`** method of `Map` instances returns a specified element from this map. If the
 value that is associated to the provided key is an object, then you will get a
 reference to that object and any change made to that object will effectively
 modify it inside the `Map` object.

Try it
------

Syntax
------

```js
get(key)
```

### Parameters

`key`

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

### Return value

 The element associated with the specified key, or
 `undefined` if the key can't be found in the `Map` object.

Examples
--------

### Using get()

```js
const myMap = new Map();
myMap.set("bar", "foo");

console.log(myMap.get("bar")); // Returns "foo"
console.log(myMap.get("baz")); // Returns undefined
```

### Using get() to retrieve a reference to an object

```js
const arr = [];
const myMap = new Map();
myMap.set("bar", arr);

myMap.get("bar").push("foo");

console.log(arr); // ["foo"]
console.log(myMap.get("bar")); // ["foo"]
```

Note that the map holding a reference to the original object effectively means the object cannot be garbage-collected, which may lead to unexpected memory issues. If you want the object stored in the map to have the same lifespan as the original one, consider using a `WeakMap`.

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

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

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

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

See also
--------

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


Map[@@species] - JavaScript

Map[@@species]
==============

The **`Map[@@species]`** static accessor property is an unused accessor property specifying how to copy `Map` objects.

Syntax
------

```js
Map[Symbol.species]
```

### Return value

The value of the constructor (`this`) on which `get @@species` was called. The return value is used to construct copied `Map` instances.

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

The `@@species` accessor property returns the default constructor for `Map` objects. Subclass constructors may override it to change the constructor assignment.

**Note:** This property is currently unused by all `Map` methods.

Examples
--------

### Species in ordinary objects

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

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

### Species in derived objects

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

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-map-@@species |

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

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

See also
--------

* `Map`
* `Symbol.species`


Uint16Array() constructor - JavaScript

Uint16Array() constructor
=========================

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

Syntax
------

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

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

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

### Parameters

See `TypedArray`.

### Exceptions

See `TypedArray`.

Examples
--------

### Different ways to create a Uint16Array

```js
// From a length
const uint16 = new Uint16Array(2);
uint16[0] = 42;
console.log(uint16[0]); // 42
console.log(uint16.length); // 2
console.log(uint16.BYTES\_PER\_ELEMENT); // 2

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

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

// From an ArrayBuffer
const buffer = new ArrayBuffer(16);
const z = new Uint16Array(buffer, 2, 4);
console.log(z.byteOffset); // 2

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

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

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

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

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

See also
--------

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


TypedArray.prototype.subarray() - JavaScript

TypedArray.prototype.subarray()
===============================

 The **`subarray()`** method of `TypedArray` instances returns a new typed array
 on the same `ArrayBuffer` store and with the same element types as for this
 typed array. The begin offset is **inclusive** and the end
 offset is **exclusive**.

Try it
------

Syntax
------

```js
subarray()
subarray(begin)
subarray(begin, end)
```

### Parameters

`begin` Optional

 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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.subarray |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.subarray` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `ArrayBuffer`


TypedArray.prototype.every() - JavaScript

TypedArray.prototype.every()
============================

The **`every()`** method of `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 `Array.prototype.every()`.

Try it
------

Syntax
------

```js
every(callbackFn)
every(callbackFn, thisArg)
```

### Parameters

`callbackFn`

A function to execute for each element in the typed array. It should return a truthy value to indicate the element passes the test, and a 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

A value to use as `this` when executing `callbackFn`. See iterative methods.

### Return value

`true` unless `callbackFn` returns a falsy value for a typed array element, in which case `false` is immediately returned.

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.every |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.every` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.prototype.forEach()`
* `TypedArray.prototype.some()`
* `TypedArray.prototype.find()`
* `Array.prototype.every()`


TypedArray.prototype.at() - JavaScript

TypedArray.prototype.at()
=========================

The **`at()`** method of `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 `Array.prototype.at()`.

Try it
------

Syntax
------

```js
at(index)
```

### Parameters

`index`

Zero-based index of the typed array element to be returned, converted to an integer. 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 `undefined` if `index < -array.length` or `index >= array.length` without attempting to access the corresponding property.

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.at |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.at` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.prototype.findIndex()`
* `TypedArray.prototype.indexOf()`
* `TypedArray.prototype.with()`
* `Array.prototype.at()`
* `String.prototype.at()`


TypedArray.prototype.includes() - JavaScript

TypedArray.prototype.includes()
===============================

The **`includes()`** method of `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 `Array.prototype.includes()`.

Try it
------

Syntax
------

```js
includes(searchElement)
includes(searchElement, fromIndex)
```

### Parameters

`searchElement`

The value to search for.

`fromIndex` Optional

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.includes |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.includes` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.prototype.indexOf()`
* `TypedArray.prototype.find()`
* `TypedArray.prototype.findIndex()`
* `Array.prototype.includes()`
* `String.prototype.includes()`


TypedArray[@@species] - JavaScript

TypedArray[@@species]
=====================

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. Avoid relying on it if possible.

Syntax
------

```js
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 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()` and `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]`, 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 `BigInt64Array` from a `Float64Array`, or create a non-BigInt array from a BigInt array. Doing so throws a `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 and V8, the content type match is not checked. Only Safari will throw a `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 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 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
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-%typedarray%-@@species |

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

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

See also
--------

* `TypedArray`
* `Symbol.species`


TypedArray.prototype.reduceRight() - JavaScript

TypedArray.prototype.reduceRight()
==================================

The **`reduceRight()`** method of `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 `Array.prototype.reduceRight()`.

Try it
------

Syntax
------

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.reduceright |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.reduceRight` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.prototype.map()`
* `TypedArray.prototype.reduce()`
* `Array.prototype.reduceRight()`
* `Object.groupBy()`
* `Map.groupBy()`


TypedArray.prototype.entries() - JavaScript

TypedArray.prototype.entries()
==============================

The **`entries()`** method of `TypedArray` instances returns a new *array iterator* object that contains the key/value pairs for each index in the typed array. This method has the same algorithm as `Array.prototype.entries()`.

Try it
------

Syntax
------

```js
entries()
```

### Parameters

None.

### Return value

A new iterable iterator object.

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.entries |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.entries` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.prototype.keys()`
* `TypedArray.prototype.values()`
* `TypedArray.prototype[@@iterator]()`
* `Array.prototype.entries()`
* Iteration protocols


TypedArray.from() - JavaScript

TypedArray.from()
=================

 The **`TypedArray.from()`** static method creates a new
 typed array
 from an array-like or iterable object. This method is nearly the same as
 `Array.from()`.

Try it
------

Syntax
------

```js
TypedArray.from(arrayLike, mapFn)
TypedArray.from(arrayLike, mapFn, thisArg)
```

Where `TypedArray` is one of:

* `Int8Array`
* `Uint8Array`
* `Uint8ClampedArray`
* `Int16Array`
* `Uint16Array`
* `Int32Array`
* `Uint32Array`
* `Float32Array`
* `Float64Array`
* `BigInt64Array`
* `BigUint64Array`
### Parameters

`arrayLike`

An iterable or array-like object to convert to a typed array.

`mapFn` Optional

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

Value to use as `this` when executing `mapFn`.

### Return value

A new `TypedArray` instance.

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

See `Array.from()` for more details.

There are some subtle distinctions between `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 `TypeError`, while `Array.from()` defaults to creating a new `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 `Proxy` objects, it calls `handler.set()` to create new elements rather than `handler.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
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.from |

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

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

See also
--------

* Polyfill of `TypedArray.from` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.of()`
* `TypedArray.prototype.map()`
* `Array.from()`


TypedArray.prototype[@@iterator]() - JavaScript

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

The **`[@@iterator]()`** method of `TypedArray` instances implements the iterable protocol and allows typed arrays to be consumed by most syntaxes expecting iterables, such as the spread syntax and `for...of` loops. It returns an array iterator object 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 `TypedArray.prototype.values` property.

Try it
------

Syntax
------

```js
typedArray[Symbol.iterator]()
```

### Parameters

None.

### Return value

The same return value as `TypedArray.prototype.values()`: a new iterable iterator object 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, 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
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype-@@iterator |

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

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

See also
--------

* Polyfill of `TypedArray.prototype[@@iterator]` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.prototype.entries()`
* `TypedArray.prototype.keys()`
* `TypedArray.prototype.values()`
* `Symbol.iterator`
* Iteration protocols


TypedArray.prototype.findLastIndex() - JavaScript

TypedArray.prototype.findLastIndex()
====================================

The **`findLastIndex()`** method of `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 `Array.prototype.findLastIndex()`.

Try it
------

Syntax
------

```js
findLastIndex(callbackFn)
findLastIndex(callbackFn, thisArg)
```

### Parameters

`callbackFn`

A function to execute for each element in the typed array. It should return a truthy value to indicate a matching element has been found, and a 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

A value to use as `this` when executing `callbackFn`. See 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 `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
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.findlastindex |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.findLastIndex` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.prototype.find()`
* `TypedArray.prototype.findIndex()`
* `TypedArray.prototype.findLast()`
* `TypedArray.prototype.indexOf()`
* `TypedArray.prototype.lastIndexOf()`
* `Array.prototype.findLastIndex()`


TypedArray.prototype.toSorted() - JavaScript

TypedArray.prototype.toSorted()
===============================

The **`toSorted()`** method of `TypedArray` instances is the copying version of the `sort()` method. It returns a new typed array with the elements sorted in ascending order. This method has the same algorithm as `Array.prototype.toSorted()`, except that it sorts the values numerically instead of as strings by default.

Syntax
------

```js
toSorted()
toSorted(compareFn)
```

### Parameters

`compareFn` Optional

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.tosorted |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.toSorted` in `core-js`
* JavaScript typed arrays guide
* `TypedArray.prototype.sort()`
* `TypedArray.prototype.toReversed()`
* `TypedArray.prototype.with()`
* `Array.prototype.toSorted()`


TypedArray.prototype.sort() - JavaScript

TypedArray.prototype.sort()
===========================

The **`sort()`** method of `TypedArray` instances sorts the elements of a typed array *in place* and returns the reference to the same typed array, now sorted. This method has the same algorithm as `Array.prototype.sort()`, except that it sorts the values numerically instead of as strings by default.

Try it
------

Syntax
------

```js
sort()
sort(compareFn)
```

### Parameters

`compareFn` Optional

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*, and no copy is made.

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.sort |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.sort` with modern behavior like stable sort in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.prototype.reverse()`
* `TypedArray.prototype.toSorted()`
* `Array.prototype.sort()`


TypedArray.prototype.toString() - JavaScript

TypedArray.prototype.toString()
===============================

The **`toString()`** method of `TypedArray` instances returns a string representing the specified typed array and its elements. This method has the same algorithm as `Array.prototype.toString()`.

Try it
------

Syntax
------

```js
toString()
```

### Parameters

None.

### Return value

A string representing the elements of the typed array.

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.tostring |

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

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

See also
--------

* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.prototype.join()`
* `TypedArray.prototype.toLocaleString()`
* `Array.prototype.toString()`
* `String.prototype.toString()`


TypedArray.prototype.length - JavaScript

TypedArray.prototype.length
===========================

The **`length`** accessor property of `TypedArray` instances returns the length (in elements) of this typed array.

Try it
------

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 `ArrayBuffer` will be returned. *TypedArray* is one of the 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
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-%typedarray%.prototype.length |

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

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

See also
--------

* JavaScript typed arrays guide
* `TypedArray`


TypedArray.prototype.findIndex() - JavaScript

TypedArray.prototype.findIndex()
================================

The **`findIndex()`** method of `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 `Array.prototype.findIndex()`.

Try it
------

Syntax
------

```js
findIndex(callbackFn)
findIndex(callbackFn, thisArg)
```

### Parameters

`callbackFn`

A function to execute for each element in the typed array. It should return a truthy value to indicate a matching element has been found, and a 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

A value to use as `this` when executing `callbackFn`. See iterative methods.

### Return value

The index of the first element in the typed array that passes the test. Otherwise, `-1`.

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.findindex |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.findIndex` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.prototype.find()`
* `TypedArray.prototype.findLast()`
* `TypedArray.prototype.findLastIndex()`
* `TypedArray.prototype.indexOf()`
* `TypedArray.prototype.lastIndexOf()`
* `Array.prototype.findIndex()`


TypedArray.prototype.set() - JavaScript

TypedArray.prototype.set()
==========================

 The **`set()`** method of `TypedArray` instances stores multiple values in the typed
 array, reading input values from a specified array.

Try it
------

Syntax
------

```js
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
 `ArrayBuffer`; the JavaScript engine will intelligently
 **copy** the source range of the buffer to the destination range.

`targetOffset` Optional

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

### Exceptions

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.set |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.set` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `ArrayBuffer`


TypedArray.prototype.copyWithin() - JavaScript

TypedArray.prototype.copyWithin()
=================================

The **`copyWithin()`** method of `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 `Array.prototype.copyWithin()`.

Try it
------

Syntax
------

```js
copyWithin(target, start)
copyWithin(target, start, end)
```

### Parameters

`target`

Zero-based index at which to copy the sequence to, converted to an integer. 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.

`end` Optional

Zero-based index at which to end copying elements from, converted to an integer. `copyWithin()` copies up to but not including `end`.

### Return value

The modified typed array.

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.copywithin |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.copyWithin` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `Array.prototype.copyWithin()`


TypedArray.prototype.filter() - JavaScript

TypedArray.prototype.filter()
=============================

The **`filter()`** method of `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 `Array.prototype.filter()`.

Try it
------

Syntax
------

```js
filter(callbackFn)
filter(callbackFn, thisArg)
```

### Parameters

`callbackFn`

A function to execute for each element in the typed array. It should return a truthy value to keep the element in the resulting typed array, and a 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

A value to use as `this` when executing `callbackFn`. See 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 `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
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.filter |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.filter` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.prototype.forEach()`
* `TypedArray.prototype.every()`
* `TypedArray.prototype.map()`
* `TypedArray.prototype.some()`
* `TypedArray.prototype.reduce()`
* `Array.prototype.filter()`


TypedArray.prototype.values() - JavaScript

TypedArray.prototype.values()
=============================

The **`values()`** method of `TypedArray` instances returns a new *array iterator* object that iterates the value of each item in the typed array. This method has the same algorithm as `Array.prototype.values()`.

Try it
------

Syntax
------

```js
values()
```

### Parameters

None.

### Return value

A new iterable iterator object.

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.values |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.values` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.prototype.entries()`
* `TypedArray.prototype.keys()`
* `TypedArray.prototype[@@iterator]()`
* `Array.prototype.values()`
* Iteration protocols


TypedArray.prototype.byteLength - JavaScript

TypedArray.prototype.byteLength
===============================

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

Try it
------

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

The `byteLength` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when 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.

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-%typedarray%.prototype.bytelength |

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

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

See also
--------

* JavaScript typed arrays guide
* `TypedArray`


TypedArray.prototype.findLast() - JavaScript

TypedArray.prototype.findLast()
===============================

The **`findLast()`** method of `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, `undefined` is returned. This method has the same algorithm as `Array.prototype.findLast()`.

Try it
------

Syntax
------

```js
findLast(callbackFn)
findLast(callbackFn, thisArg)
```

### Parameters

`callbackFn`

A function to execute for each element in the typed array. It should return a truthy value to indicate a matching element has been found, and a 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

A value to use as `this` when executing `callbackFn`. See iterative methods.

### Return value

The last (highest-index) element in the typed array that satisfies the provided testing function; `undefined` if no matching element is found.

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.findlast |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.findLast` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.prototype.find()`
* `TypedArray.prototype.findIndex()`
* `TypedArray.prototype.findLastIndex()`
* `TypedArray.prototype.includes()`
* `TypedArray.prototype.filter()`
* `TypedArray.prototype.every()`
* `TypedArray.prototype.some()`
* `Array.prototype.findLast()`


TypedArray.prototype.with() - JavaScript

TypedArray.prototype.with()
===========================

The **`with()`** method of `TypedArray` instances is the copying version of using the 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 `Array.prototype.with()`.

Syntax
------

```js
arrayInstance.with(index, value)
```

### Parameters

`index`

Zero-based index at which to change the typed array, converted to an integer.

`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

`RangeError`

Thrown if `index >= array.length` or `index < -array.length`.

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.with |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.with` in `core-js`
* JavaScript typed arrays guide
* `TypedArray.prototype.toReversed()`
* `TypedArray.prototype.toSorted()`
* `TypedArray.prototype.at()`
* `Array.prototype.with()`


TypedArray.prototype.toLocaleString() - JavaScript

TypedArray.prototype.toLocaleString()
=====================================

The **`toLocaleString()`** method of `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 `Array.prototype.toLocaleString()`.

Try it
------

Syntax
------

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

### Parameters

`locales` Optional

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.

`options` Optional

An object with configuration properties. See `Number.prototype.toLocaleString()`.

### Return value

A string representing the elements of the typed array.

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.tolocalestring |

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

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

See also
--------

* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.prototype.toString()`
* `Array.prototype.toLocaleString()`
* `Intl`
* `Intl.ListFormat`
* `Number.prototype.toLocaleString()`


TypedArray.prototype.find() - JavaScript

TypedArray.prototype.find()
===========================

The **`find()`** method of `TypedArray` instances returns the first element in the provided typed array that satisfies the provided testing function. If no values satisfy the testing function, `undefined` is returned. This method has the same algorithm as `Array.prototype.find()`.

Try it
------

Syntax
------

```js
find(callbackFn)
find(callbackFn, thisArg)
```

### Parameters

`callbackFn`

A function to execute for each element in the typed array. It should return a truthy value to indicate a matching element has been found, and a 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

A value to use as `this` when executing `callbackFn`. See iterative methods.

### Return value

 The first element in the typed array that satisfies the provided testing function.
 Otherwise, `undefined` is returned.

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.find |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.find` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.prototype.findIndex()`
* `TypedArray.prototype.findLast()`
* `TypedArray.prototype.findLastIndex()`
* `TypedArray.prototype.includes()`
* `TypedArray.prototype.filter()`
* `TypedArray.prototype.every()`
* `TypedArray.prototype.some()`
* `Array.prototype.find()`


TypedArray.prototype.some() - JavaScript

TypedArray.prototype.some()
===========================

The **`some()`** method of `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 `Array.prototype.some()`.

Try it
------

Syntax
------

```js
some(callbackFn)
some(callbackFn, thisArg)
```

### Parameters

`callbackFn`

A function to execute for each element in the typed array. It should return a truthy value to indicate the element passes the test, and a 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

A value to use as `this` when executing `callbackFn`. See iterative methods.

### Return value

`false` unless `callbackFn` returns a truthy value for a typed array element, in which case `true` is immediately returned.

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.some |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.some` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.prototype.every()`
* `TypedArray.prototype.forEach()`
* `TypedArray.prototype.find()`
* `TypedArray.prototype.includes()`
* `Array.prototype.some()`


TypedArray.prototype.map() - JavaScript

TypedArray.prototype.map()
==========================

The **`map()`** method of `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 `Array.prototype.map()`.

Try it
------

Syntax
------

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

A value to use as `this` when executing `callbackFn`. See iterative methods.

### Return value

A new typed array with each element being the result of the callback function.

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.map |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.map` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.prototype.forEach()`
* `TypedArray.from()`
* `Array.prototype.map()`
* `Map`


TypedArray.prototype.buffer - JavaScript

TypedArray.prototype.buffer
===========================

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

Try it
------

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

The `buffer` property is an accessor property whose set accessor function is `undefined`, meaning that you can only read this property. The value is established when the *TypedArray* is constructed and cannot be changed. *TypedArray* is one of the 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
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-%typedarray%.prototype.buffer |

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

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

See also
--------

* JavaScript typed arrays guide
* `TypedArray`


TypedArray.prototype.keys() - JavaScript

TypedArray.prototype.keys()
===========================

The **`keys()`** method of `TypedArray` instances returns a new *array iterator* object that contains the keys for each index in the typed array. This method has the same algorithm as `Array.prototype.keys()`.

Try it
------

Syntax
------

```js
keys()
```

### Parameters

None.

### Return value

A new iterable iterator object.

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.keys |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.keys` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.prototype.entries()`
* `TypedArray.prototype.values()`
* `TypedArray.prototype[@@iterator]()`
* `Array.prototype.keys()`
* Iteration protocols


TypedArray.prototype.byteOffset - JavaScript

TypedArray.prototype.byteOffset
===============================

The **`byteOffset`** accessor property of `TypedArray` instances returns the offset (in bytes) of this typed array from the start of its `ArrayBuffer` or `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.

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-get-%typedarray%.prototype.byteoffset |

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

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

See also
--------

* JavaScript typed arrays guide
* `TypedArray`


TypedArray.prototype.reverse() - JavaScript

TypedArray.prototype.reverse()
==============================

The **`reverse()`** method of `TypedArray` instances reverses a typed array *in place* 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 `Array.prototype.reverse()`.

Try it
------

Syntax
------

```js
reverse()
```

### Parameters

None.

### Return value

The reference to the original typed array, now reversed. Note that the typed array is reversed *in place*, and no copy is made.

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.reverse |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.reverse` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.prototype.join()`
* `TypedArray.prototype.sort()`
* `TypedArray.prototype.toReversed()`
* `Array.prototype.reverse()`


TypedArray.prototype.indexOf() - JavaScript

TypedArray.prototype.indexOf()
==============================

The **`indexOf()`** method of `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 `Array.prototype.indexOf()`.

Try it
------

Syntax
------

```js
indexOf(searchElement)
indexOf(searchElement, fromIndex)
```

### Parameters

`searchElement`

Element to locate in the typed array.

`fromIndex` Optional

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

### Return value

The first index of `searchElement` in the typed array; `-1` if not found.

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.indexof |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.indexOf` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.prototype.findIndex()`
* `TypedArray.prototype.findLastIndex()`
* `TypedArray.prototype.lastIndexOf()`
* `Array.prototype.indexOf()`
* `String.prototype.indexOf()`


TypedArray.prototype.lastIndexOf() - JavaScript

TypedArray.prototype.lastIndexOf()
==================================

The **`lastIndexOf()`** method of `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 `Array.prototype.lastIndexOf()`.

Try it
------

Syntax
------

```js
lastIndexOf(searchElement)
lastIndexOf(searchElement, fromIndex)
```

### Parameters

`searchElement`

Element to locate in the typed array.

`fromIndex` Optional

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

### Return value

The last index of `searchElement` in the typed array; `-1` if not found.

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.lastindexof |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.lastIndexOf` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.prototype.findIndex()`
* `TypedArray.prototype.findLastIndex()`
* `TypedArray.prototype.indexOf()`
* `Array.prototype.lastIndexOf()`
* `String.prototype.lastIndexOf()`


TypedArray.BYTES_PER_ELEMENT - JavaScript

TypedArray.BYTES\_PER\_ELEMENT
==============================

The **`TypedArray.BYTES_PER_ELEMENT`** static data property represents the size in bytes of each element in a typed array.

Try it
------

Value
-----

A number whose value depends on the type of `TypedArray`.

| Property attributes of `TypedArray.BYTES_PER_ELEMENT` |
| --- |
| Writable | no |
| Enumerable | no |
| Configurable | no |

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-typedarray.bytes\_per\_element |

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

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

See also
--------

* JavaScript typed arrays guide
* `TypedArray`


TypedArray.prototype.forEach() - JavaScript

TypedArray.prototype.forEach()
==============================

The **`forEach()`** method of `TypedArray` instances executes a provided function once for each typed array element. This method has the same algorithm as `Array.prototype.forEach()`.

Try it
------

Syntax
------

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

A value to use as `this` when executing `callbackFn`. See iterative methods.

### Return value

None (`undefined`).

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.foreach |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.forEach` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.prototype.find()`
* `TypedArray.prototype.map()`
* `TypedArray.prototype.filter()`
* `TypedArray.prototype.every()`
* `TypedArray.prototype.some()`
* `Array.prototype.forEach()`
* `Map.prototype.forEach()`
* `Set.prototype.forEach()`


TypedArray.of() - JavaScript

TypedArray.of()
===============

 The **`TypedArray.of()`** static method creates a new
 typed array from a variable number of arguments. This method is nearly the same as
 `Array.of()`.

Try it
------

Syntax
------

```js
TypedArray.of()
TypedArray.of(element1)
TypedArray.of(element1, element2)
TypedArray.of(element1, element2, /\* …, \*/ elementN)
```

Where `TypedArray` is one of:

* `Int8Array`
* `Uint8Array`
* `Uint8ClampedArray`
* `Int16Array`
* `Uint16Array`
* `Int32Array`
* `Uint32Array`
* `Float32Array`
* `Float64Array`
* `BigInt64Array`
* `BigUint64Array`
### Parameters

`element1`, …, `elementN`

Elements used to create the typed array.

### Return value

A new `TypedArray` instance.

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

 See `Array.of()` for more details. There are some subtle distinctions between `Array.of()` and
 `TypedArray.of()`:

* If the `this` value passed to `TypedArray.of()` is not a constructor, `TypedArray.from()` will throw a `TypeError`, while `Array.of()` defaults to creating a new `Array`.
* `TypedArray.of()` uses `[[Set]]` while `Array.of()` uses `[[DefineOwnProperty]]`. Hence, when working with `Proxy` objects, it calls `handler.set()` to create new elements rather than `handler.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
--------------

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.of |

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

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

See also
--------

* Polyfill of `TypedArray.of` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.from()`
* `Array.of()`


TypedArray.prototype.reduce() - JavaScript

TypedArray.prototype.reduce()
=============================

The **`reduce()`** method of `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 `Array.prototype.reduce()`.

Try it
------

Syntax
------

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

 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

`TypeError`

Thrown if the typed array contains no elements and `initialValue` is not provided.

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

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.reduce |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.reduce` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.prototype.map()`
* `TypedArray.prototype.reduceRight()`
* `Array.prototype.reduce()`
* `Object.groupBy()`
* `Map.groupBy()`


TypedArray.prototype.join() - JavaScript

TypedArray.prototype.join()
===========================

The **`join()`** method of `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 `Array.prototype.join()`.

Try it
------

Syntax
------

```js
join()
join(separator)
```

### Parameters

`separator` Optional

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-%typedarray%.prototype.join |

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

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

See also
--------

* Polyfill of `TypedArray.prototype.join` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `TypedArray.prototype.toString()`
* `Array.prototype.join()`
* `String.prototype.split()`