Math.log10() - JavaScript

Math.log10()
============

The **`Math.log10()`** static method returns the base 10 logarithm of a number. That is

∀
x
>
0
,

𝙼𝚊𝚝𝚑.𝚕𝚘𝚐𝟷𝟶
(
𝚡
)

=

log
10

(
x
)
=
the unique
y
 such that

10
y

=
x

\forall x > 0,;\mathtt{\operatorname{Math.log10}(x)} = \log\_{10}(x) = \text{the unique } y \text{ such that } 10^y = x

Try it
------

Syntax
------

```js
Math.log10(x)
```

### Parameters

`x`

A number greater than or equal to 0.

### Return value

The base 10 logarithm of `x`. If `x < 0`, returns `NaN`.

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

Because `log10()` is a static method of `Math`, you always use it as `Math.log10()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

This function is the equivalent of `Math.log(x) / Math.log(10)`. For `log10(e)`, use the constant `Math.LOG10E`, which is 1 / `Math.LN10`.

Examples
--------

### Using Math.log10()

```js
Math.log10(-2); // NaN
Math.log10(-0); // -Infinity
Math.log10(0); // -Infinity
Math.log10(1); // 0
Math.log10(2); // 0.3010299956639812
Math.log10(100000); // 5
Math.log10(Infinity); // Infinity
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.log10 |

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

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

See also
--------

* Polyfill of `Math.log10` in `core-js`
* `Math.exp()`
* `Math.log()`
* `Math.log1p()`
* `Math.log2()`
* `Math.pow()`


Math.acos() - JavaScript

Math.acos()
===========

The **`Math.acos()`** static method returns the inverse cosine (in radians) of a number. That is,

∀
x
∊
[

−
1

,
1
]
,

𝙼𝚊𝚝𝚑.𝚊𝚌𝚘𝚜
(
𝚡
)

=
arccos
(
x
)
=
the unique
y
∊
[
0
,
π
]
 such that
cos
(
y
)
=
x

\forall x \in [{-1}, 1],;\mathtt{\operatorname{Math.acos}(x)} = \arccos(x) = \text{the unique } y \in [0, \pi] \text{ such that } \cos(y) = x

Try it
------

Syntax
------

```js
Math.acos(x)
```

### Parameters

`x`

A number between -1 and 1, inclusive, representing the angle's cosine value.

### Return value

The inverse cosine (angle in radians between 0 and π, inclusive) of `x`. If `x` is less than -1 or greater than 1, returns `NaN`.

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

Because `acos()` is a static method of `Math`, you always use it as `Math.acos()`, rather than as a method of a `Math` object you created (`Math` is not a constructor).

Examples
--------

### Using Math.acos()

```js
Math.acos(-2); // NaN
Math.acos(-1); // 3.141592653589793 (π)
Math.acos(0); // 1.5707963267948966 (π/2)
Math.acos(0.5); // 1.0471975511965979 (π/3)
Math.acos(1); // 0
Math.acos(2); // NaN
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.acos |

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

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

See also
--------

* `Math.asin()`
* `Math.atan()`
* `Math.atan2()`
* `Math.cos()`
* `Math.sin()`
* `Math.tan()`


Math.acosh() - JavaScript

Math.acosh()
============

The **`Math.acosh()`** static method returns the inverse hyperbolic cosine of a number. That is,

∀
x
≥
1
,

𝙼𝚊𝚝𝚑.𝚊𝚌𝚘𝚜𝚑
(
𝚡
)

=
arcosh
(
x
)
=
the unique
y
≥
0
 such that
cosh
(
y
)
=
x

=
ln

(

x
+

x
2

−
1

)

\begin{aligned}\forall x \geq 1,;\mathtt{\operatorname{Math.acosh}(x)} &= \operatorname{arcosh}(x) = \text{the unique } y \geq 0 \text{ such that } \cosh(y) = x\&= \ln\left(x + \sqrt{x^2 - 1}\right)\end{aligned}

Try it
------

Syntax
------

```js
Math.acosh(x)
```

### Parameters

`x`

A number greater than or equal to 1.

### Return value

The inverse hyperbolic cosine of `x`. If `x` is less than 1, returns `NaN`.

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

Because `acosh()` is a static method of `Math`, you always use it as `Math.acosh()`, rather than as a method of a `Math` object you created (`Math` is no constructor).

Examples
--------

### Using Math.acosh()

```js
Math.acosh(0); // NaN
Math.acosh(1); // 0
Math.acosh(2); // 1.3169578969248166
Math.acosh(Infinity); // Infinity
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-math.acosh |

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

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

See also
--------

* Polyfill of `Math.acosh` in `core-js`
* `Math.asinh()`
* `Math.atanh()`
* `Math.cosh()`
* `Math.sinh()`
* `Math.tanh()`


Uint8Array() constructor - JavaScript

Uint8Array() constructor
========================

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

Syntax
------

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

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

**Note:** `Uint8Array()` 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 Uint8Array

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

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

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

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

// From an iterable
const iterable = (function\* () {
  yield\* [1, 2, 3];
})();
const uint8FromIterable = new Uint8Array(iterable);
console.log(uint8FromIterable);
// Uint8Array [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 `Uint8Array` in `core-js`
* JavaScript typed arrays guide
* `TypedArray`
* `ArrayBuffer`
* `DataView`


EvalError() constructor - JavaScript

EvalError() constructor
=======================

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

Syntax
------

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

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

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

### Parameters

`message` Optional

Human-readable description of the error.

`options` Optional

An object that has the following properties:

`cause` Optional

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

`fileName` Optional
Non-standard

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

`lineNumber` Optional
Non-standard

The line number of the code that caused the exception

Examples
--------

`EvalError` is not used in the current ECMAScript specification and will
 thus not be thrown by the runtime. However, the object itself remains for backwards
 compatibility with earlier versions of the specification.

### Creating an EvalError

```js
try {
  throw new EvalError("Hello");
} catch (e) {
  console.log(e instanceof EvalError); // true
  console.log(e.message); // "Hello"
  console.log(e.name); // "EvalError"
  console.log(e.stack); // Stack of the error
}
```

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

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

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

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

See also
--------

* `Error`
* `eval()`


ReferenceError() constructor - JavaScript

ReferenceError() constructor
============================

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

Syntax
------

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

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

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

### Parameters

`message` Optional

Human-readable description of the error.

`options` Optional

An object that has the following properties:

`cause` Optional

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

`fileName` Optional
Non-standard

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

`lineNumber` Optional
Non-standard

The line number of the code that caused the exception

Examples
--------

### Catching a ReferenceError

```js
try {
  let a = undefinedVariable;
} catch (e) {
  console.log(e instanceof ReferenceError); // true
  console.log(e.message); // "undefinedVariable is not defined"
  console.log(e.name); // "ReferenceError"
  console.log(e.stack); // Stack of the error
}
```

### Creating a ReferenceError

```js
try {
  throw new ReferenceError("Hello");
} catch (e) {
  console.log(e instanceof ReferenceError); // true
  console.log(e.message); // "Hello"
  console.log(e.name); // "ReferenceError"
  console.log(e.stack); // Stack of the error
}
```

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

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

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

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

See also
--------

* `Error`


Array.prototype.findLast() - JavaScript

Array.prototype.findLast()
==========================

 The **`findLast()`** method of `Array` instances iterates the 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.

If you need to find:

* the *first* element that matches, use `find()`.
* the *index* of the last matching element in the array, use `findLastIndex()`.
* the *index of a value*, use `indexOf()`.
 (It's similar to `findIndex()`, but checks each element for equality with the value instead of using a testing function.)
* whether a value *exists* in an array, use `includes()`.
 Again, it checks each element for equality with the value instead of using a testing function.
* if any element satisfies the provided testing function, use `some()`.
Try it
------

Syntax
------

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

### Parameters

`callbackFn`

A function to execute for each element in the 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 array.

`index`

The index of the current element being processed in the array.

`array`

The 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 array that satisfies the provided testing function; `undefined` if no matching element is found.

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

The `findLast()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array in descending-index order, until `callbackFn` returns a truthy value. `findLast()` then returns that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `findLast()` returns `undefined`. Read the iterative methods section for more information about how these methods work in general.

`callbackFn` is invoked for *every* index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`.

The `findLast()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

Examples
--------

### Find last object in an array matching on element properties

This example shows how you might create a test based on the properties of array elements.

```js
const inventory = [
  { name: "apples", quantity: 2 },
  { name: "bananas", quantity: 0 },
  { name: "fish", quantity: 1 },
  { name: "cherries", quantity: 5 },
];

// return true inventory stock is low
function isNotEnough(item) {
  return item.quantity < 2;
}

console.log(inventory.findLast(isNotEnough));
// { name: "fish", quantity: 1 }
```

#### Using arrow function and destructuring

The previous example might be written using an arrow function and object destructuring:

```js
const inventory = [
  { name: "apples", quantity: 2 },
  { name: "bananas", quantity: 0 },
  { name: "fish", quantity: 1 },
  { name: "cherries", quantity: 5 },
];

const result = inventory.findLast(({ quantity }) => quantity < 2);

console.log(result);
// { name: "fish", quantity: 1 }
```

### Find the last prime number in an array

The following example returns the last element in the 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;
}

console.log([4, 6, 8, 12].findLast(isPrime)); // undefined, not found
console.log([4, 5, 7, 8, 9, 11, 12].findLast(isPrime)); // 11
```

### Using the third argument of callbackFn

The `array` argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses `filter()` to extract the positive values and then uses `findLast()` to find the last element that is less than its neighbors.

```js
const numbers = [3, -1, 1, 4, 1, 5, 9, 2, 6];
const lastTrough = numbers
  .filter((num) => num > 0)
  .findLast((num, idx, arr) => {
    // Without the arr argument, there's no way to easily access the
    // intermediate array without saving it to a variable.
    if (idx > 0 && num >= arr[idx - 1]) return false;
    if (idx < arr.length - 1 && num >= arr[idx + 1]) return false;
    return true;
  });
console.log(lastTrough); // 2
```

### Using findLast() on sparse arrays

Empty slots in sparse arrays *are* visited, and are treated the same as `undefined`.

```js
// Declare array with no elements at indexes 2, 3, and 4
const array = [0, 1, , , , 5, 6];

// Shows all indexes, not just those with assigned values
array.findLast((value, index) => {
  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 undefined
// Visited index 3 with value undefined
// Visited index 2 with value undefined
// Visited index 1 with value 1
// Visited index 0 with value 0

// Shows all indexes, including deleted
array.findLast((value, index) => {
  // Delete element 5 on first iteration
  if (index === 6) {
    console.log(`Deleting array[5] with value ${array[5]}`);
    delete array[5];
  }
  // Element 5 is still visited even though deleted
  console.log(`Visited index ${index} with value ${value}`);
});
// Deleting array[5] with value 5
// Visited index 6 with value 6
// Visited index 5 with value undefined
// Visited index 4 with value undefined
// Visited index 3 with value undefined
// Visited index 2 with value undefined
// Visited index 1 with value 1
// Visited index 0 with value 0
```

### Calling findLast() on non-array objects

The `findLast()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`.

```js
const arrayLike = {
  length: 3,
  0: 2,
  1: 7.3,
  2: 4,
  3: 3, // ignored by findLast() since length is 3
};
console.log(
  Array.prototype.findLast.call(arrayLike, (x) => Number.isInteger(x)),
); // 4
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.findlast |

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

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

See also
--------

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


Array.prototype.toSpliced() - JavaScript

Array.prototype.toSpliced()
===========================

The **`toSpliced()`** method of `Array` instances is the copying version of the `splice()` method. It returns a new array with some elements removed and/or replaced at a given index.

Syntax
------

```js
toSpliced(start)
toSpliced(start, deleteCount)
toSpliced(start, deleteCount, item1)
toSpliced(start, deleteCount, item1, item2)
toSpliced(start, deleteCount, item1, item2, /\* …, \*/ itemN)
```

### Parameters

`start`

Zero-based index at which to start changing the array, converted to an integer.

* Negative index counts back from the end of the array — if `start < 0`, `start + array.length` is used.
* If `start < -array.length` or `start` is omitted, `0` is used.
* If `start >= array.length`, no element will be deleted, but the method will behave as an adding function, adding as many elements as provided.

`deleteCount` Optional

An integer indicating the number of elements in the array to remove from `start`.

If `deleteCount` is omitted, or if its value is greater than or equal to the number of elements after the position specified by `start`, then all the elements from `start` to the end of the array will be deleted. However, if you wish to pass any `itemN` parameter, you should pass `Infinity` as `deleteCount` to delete all elements after `start`, because an explicit `undefined` gets converted to `0`.

 If `deleteCount` is `0` or negative, no elements are removed.
 In this case, you should specify at least one new element (see below).

`item1`, …, `itemN` Optional

The elements to add to the array, beginning from `start`.

If you do not specify any elements, `toSpliced()` will only remove elements from the array.

### Return value

A new array that consists of all elements before `start`, `item1`, `item2`, …, `itemN`, and all elements after `start + deleteCount`.

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

The `toSpliced()` method, like `splice()`, does multiple things at once: it removes the given number of elements from the array, starting at a given index, and then inserts the given elements at the same index. However, it returns a new array instead of modifying the original array. The deleted elements therefore are not returned from this method.

The `toSpliced()` method never produces a sparse array. If the source array is sparse, the empty slots will be replaced with `undefined` in the new array.

The `toSpliced()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

Examples
--------

### Deleting, adding, and replacing elements

You can use `toSpliced()` to delete, add, and replace elements in an array and create a new array more efficiently than using `slice()` and `concat()`.

```js
const months = ["Jan", "Mar", "Apr", "May"];

// Inserting an element at index 1
const months2 = months.toSpliced(1, 0, "Feb");
console.log(months2); // ["Jan", "Feb", "Mar", "Apr", "May"]

// Deleting two elements starting from index 2
const months3 = months2.toSpliced(2, 2);
console.log(months3); // ["Jan", "Feb", "May"]

// Replacing one element at index 1 with two new elements
const months4 = months3.toSpliced(1, 1, "Feb", "Mar");
console.log(months4); // ["Jan", "Feb", "Mar", "May"]

// Original array is not modified
console.log(months); // ["Jan", "Mar", "Apr", "May"]
```

### Using toSpliced() on sparse arrays

The `toSpliced()` method always creates a dense array.

```js
const arr = [1, , 3, 4, , 6];
console.log(arr.toSpliced(1, 2)); // [1, 4, undefined, 6]
```

### Calling toSpliced() on non-array objects

The `toSpliced()` method reads the `length` property of `this`. It then reads the integer-keyed properties needed and writes them into the new array.

```js
const arrayLike = {
  length: 3,
  unrelated: "foo",
  0: 5,
  2: 4,
};
console.log(Array.prototype.toSpliced.call(arrayLike, 0, 1, 2, 3));
// [2, 3, undefined, 4]
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.tospliced |

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

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

See also
--------

* Polyfill of `Array.prototype.toSpliced` in `core-js`
* `Array.prototype.splice()`
* `Array.prototype.toReversed()`
* `Array.prototype.toSorted()`
* `Array.prototype.with()`


Array.prototype.shift() - JavaScript

Array.prototype.shift()
=======================

 The **`shift()`** method of `Array` instances removes the **first**
 element from an array and returns that removed element. This method changes the length
 of the array.

Try it
------

Syntax
------

```js
shift()
```

### Parameters

None.

### Return value

The removed element from the array; `undefined` if the array is empty.

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

 The `shift()` method removes the element at the zeroth index and shifts the
 values at consecutive indexes down, then returns the removed value. If the
 `length` property is 0, `undefined` is returned.

The `pop()` method has similar behavior to `shift()`, but applied to the last element in an array.

The `shift()` method is a mutating method. It changes the length and the content of `this`. In case you want the value of `this` to be the same, but return a new array with the first element removed, you can use `arr.slice(1)` instead.

The `shift()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.

Examples
--------

### Removing an element from an array

 The following code displays the `myFish` array before and after removing its
 first element. It also displays the removed element:

```js
const myFish = ["angel", "clown", "mandarin", "surgeon"];

console.log("myFish before:", myFish);
// myFish before: ['angel', 'clown', 'mandarin', 'surgeon']

const shifted = myFish.shift();

console.log("myFish after:", myFish);
// myFish after: ['clown', 'mandarin', 'surgeon']

console.log("Removed this element:", shifted);
// Removed this element: angel
```

### Using shift() method in while loop

 The shift() method is often used in condition inside while loop. In the following
 example every iteration will remove the next element from an array, until it is empty:

```js
const names = ["Andrew", "Tyrone", "Paul", "Maria", "Gayatri"];

while (typeof (i = names.shift()) !== "undefined") {
  console.log(i);
}
// Andrew, Tyrone, Paul, Maria, Gayatri
```

### Calling shift() on non-array objects

The `shift()` method reads the `length` property of `this`. If the normalized length is 0, `length` is set to `0` again (whereas it may be negative or `undefined` before). Otherwise, the property at `0` is returned, and the rest of the properties are shifted left by one. The `length` property is decremented by one.

```js
const arrayLike = {
  length: 3,
  unrelated: "foo",
  2: 4,
};
console.log(Array.prototype.shift.call(arrayLike));
// undefined, because it is an empty slot
console.log(arrayLike);
// { '1': 4, length: 2, unrelated: 'foo' }

const plainObj = {};
// There's no length property, so the length is 0
Array.prototype.shift.call(plainObj);
console.log(plainObj);
// { length: 0 }
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.shift |

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

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

See also
--------

* Indexed collections guide
* `Array`
* `Array.prototype.push()`
* `Array.prototype.pop()`
* `Array.prototype.unshift()`
* `Array.prototype.concat()`
* `Array.prototype.splice()`


Array.from() - JavaScript

Array.from()
============

The **`Array.from()`** static method creates a new, shallow-copied `Array` instance from an iterable or array-like object.

Try it
------

Syntax
------

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

### Parameters

`arrayLike`

An iterable or array-like object to convert to an array.

`mapFn` Optional

A function to call on every element of the array. If provided, every value to be added to the array is first passed through this function, and `mapFn`'s return value is added to the array instead. The function is called with the following arguments:

`element`

The current element being processed in the array.

`index`

The index of the current element being processed in the array.

`thisArg` Optional

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

### Return value

A new `Array` instance.

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

`Array.from()` lets you create `Array`s from:

* iterable objects (objects such as `Map` and `Set`); or, if the object is not iterable,
* array-like objects (objects with a `length` property and indexed elements).

To convert an ordinary object that's not iterable or array-like to an array (by enumerating its property keys, values, or both), use `Object.keys()`, `Object.values()`, or `Object.entries()`. To convert an async iterable to an array, use `Array.fromAsync()`.

`Array.from()` never creates a sparse array. If the `arrayLike` object is missing some index properties, they become `undefined` in the new array.

`Array.from()` has an optional parameter `mapFn`, which allows you to execute a function on each element of the array being created, similar to `map()`. More clearly, `Array.from(obj, mapFn, thisArg)` has the same result as `Array.from(obj).map(mapFn, thisArg)`, except that it does not create an intermediate array, and `mapFn` only receives two arguments (`element`, `index`) without the whole array, because the array is still under construction.

**Note:** This behavior is more important for typed arrays, since the intermediate array would necessarily have values truncated to fit into the appropriate type. `Array.from()` is implemented to have the same signature as `TypedArray.from()`.

The `Array.from()` method is a generic factory method. For example, if a subclass of `Array` inherits the `from()` method, the inherited `from()` method will return new instances of the subclass instead of `Array` instances. In fact, the `this` value can be any constructor function that accepts a single argument representing the length of the new array. When an iterable is passed as `arrayLike`, the constructor is called with no arguments; when an array-like object is passed, the constructor is called with the normalized length of the array-like object. The final `length` will be set again when iteration finishes. If the `this` value is not a constructor function, the plain `Array` constructor is used instead.

Examples
--------

### Array from a String

```js
Array.from("foo");
// [ "f", "o", "o" ]
```

### Array from a Set

```js
const set = new Set(["foo", "bar", "baz", "foo"]);
Array.from(set);
// [ "foo", "bar", "baz" ]
```

### Array from a Map

```js
const map = new Map([
  [1, 2],
  [2, 4],
  [4, 8],
]);
Array.from(map);
// [[1, 2], [2, 4], [4, 8]]

const mapper = new Map([
  ["1", "a"],
  ["2", "b"],
]);
Array.from(mapper.values());
// ['a', 'b'];

Array.from(mapper.keys());
// ['1', '2'];
```

### Array from a NodeList

```js
// Create an array based on a property of DOM Elements
const images = document.querySelectorAll("img");
const sources = Array.from(images, (image) => image.src);
const insecureSources = sources.filter((link) => link.startsWith("http://"));
```

### Array from an Array-like object (arguments)

```js
function f() {
  return Array.from(arguments);
}

f(1, 2, 3);

// [ 1, 2, 3 ]
```

### Using arrow functions and Array.from()

```js
// Using an arrow function as the map function to
// manipulate the elements
Array.from([1, 2, 3], (x) => x + x);
// [2, 4, 6]

// Generate a sequence of numbers
// Since the array is initialized with `undefined` on each position,
// the value of `v` below will be `undefined`
Array.from({ length: 5 }, (v, i) => i);
// [0, 1, 2, 3, 4]
```

### Sequence generator (range)

```js
// Sequence generator function (commonly referred to as "range", e.g. Clojure, PHP, etc.)
const range = (start, stop, step) =>
  Array.from({ length: (stop - start) / step + 1 }, (\_, i) => start + i \* step);

// Generate numbers range 0..4
range(0, 4, 1);
// [0, 1, 2, 3, 4]

// Generate numbers range 1..10 with step of 2
range(1, 10, 2);
// [1, 3, 5, 7, 9]

// Generate the alphabet using Array.from making use of it being ordered as a sequence
range("A".charCodeAt(0), "Z".charCodeAt(0), 1).map((x) =>
  String.fromCharCode(x),
);
// ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
```

### Calling from() on non-array constructors

The `from()` method can be called on any constructor function that accepts a single argument representing the length of the new array.

```js
function NotArray(len) {
  console.log("NotArray called with length", len);
}

// Iterable
console.log(Array.from.call(NotArray, new Set(["foo", "bar", "baz"])));
// NotArray called with length undefined
// NotArray { '0': 'foo', '1': 'bar', '2': 'baz', length: 3 }

// Array-like
console.log(Array.from.call(NotArray, { length: 1, 0: "foo" }));
// NotArray called with length 1
// NotArray { '0': 'foo', length: 1 }
```

When the `this` value is not a constructor, a plain `Array` object is returned.

```js
console.log(Array.from.call({}, { length: 1, 0: "foo" })); // [ 'foo' ]
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.from |

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

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

See also
--------

* Polyfill of `Array.from` in `core-js`
* Indexed collections guide
* `Array`
* `Array()`
* `Array.of()`
* `Array.fromAsync()`
* `Array.prototype.map()`
* `TypedArray.from()`


Array.prototype.flat() - JavaScript

Array.prototype.flat()
======================

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

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

* Learn more
* See full compatibility
* Report feedback

 The **`flat()`** method of `Array` instances creates a new array with all sub-array
 elements concatenated into it recursively up to the specified depth.

Try it
------

Syntax
------

```js
flat()
flat(depth)
```

### Parameters

`depth` Optional

 The depth level specifying how deep a nested array structure should be flattened.
 Defaults to 1.

### Return value

A new array with the sub-array elements concatenated into it.

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

The `flat()` method is a copying method. It does not alter `this` but instead returns a shallow copy that contains the same elements as the ones from the original array.

The `flat()` method ignores empty slots if the array being flattened is sparse. For example, if `depth` is 1, both empty slots in the root array and in the first level of nested arrays are ignored, but empty slots in further nested arrays are preserved with the arrays themselves.

The `flat()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, its elements must be arrays if they are to be flattened.

Examples
--------

### Flattening nested arrays

```js
const arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]

const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

const arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```

### Using flat() on sparse arrays

The `flat()` method removes empty slots in arrays:

```js
const arr5 = [1, 2, , 4, 5];
console.log(arr5.flat()); // [1, 2, 4, 5]

const array = [1, , 3, ["a", , "c"]];
console.log(array.flat()); // [ 1, 3, "a", "c" ]

const array2 = [1, , 3, ["a", , ["d", , "e"]]];
console.log(array2.flat()); // [ 1, 3, "a", ["d", empty, "e"] ]
console.log(array2.flat(2)); // [ 1, 3, "a", "d", "e"]
```

### Calling flat() on non-array objects

The `flat()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`. If the element is not an array, it's directly appended to the result. If the element is an array, it's flattened according to the `depth` parameter.

```js
const arrayLike = {
  length: 3,
  0: [1, 2],
  // Array-like objects aren't flattened
  1: { length: 2, 0: 3, 1: 4 },
  2: 5,
  3: 3, // ignored by flat() since length is 3
};
console.log(Array.prototype.flat.call(arrayLike));
// [ 1, 2, { '0': 3, '1': 4, length: 2 }, 5 ]
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.flat |

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

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

See also
--------

* Polyfill of `Array.prototype.flat` in `core-js`
* Indexed collections guide
* `Array`
* `Array.prototype.concat()`
* `Array.prototype.flatMap()`
* `Array.prototype.map()`
* `Array.prototype.reduce()`


Array.prototype.findIndex() - JavaScript

Array.prototype.findIndex()
===========================

 The **`findIndex()`** method of `Array` instances returns the index of the first element in an array that satisfies the provided testing function.
 If no elements satisfy the testing function, -1 is returned.

See also the `find()` method, which returns the first element that satisfies the testing function (rather than its index).

Try it
------

Syntax
------

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

### Parameters

`callbackFn`

A function to execute for each element in the 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 array.

`index`

The index of the current element being processed in the array.

`array`

The 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 array that passes the test. Otherwise, `-1`.

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

The `findIndex()` is an iterative method. It calls a provided `callbackFn` function once for each element in an array in ascending-index order, until `callbackFn` returns a truthy value. `findIndex()` then returns the index of that element and stops iterating through the array. If `callbackFn` never returns a truthy value, `findIndex()` returns `-1`. Read the iterative methods section for more information about how these methods work in general.

`callbackFn` is invoked for *every* index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as `undefined`.

The `findIndex()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

Examples
--------

### Find the index of a prime number in an array

The following example returns the index of the first element in the array that is a prime number, or `-1` if there is no prime number.

```js
function isPrime(element) {
  if (element % 2 === 0 || element < 2) {
    return false;
  }
  for (let factor = 3; factor <= Math.sqrt(element); factor += 2) {
    if (element % factor === 0) {
      return false;
    }
  }
  return true;
}

console.log([4, 6, 8, 9, 12].findIndex(isPrime)); // -1, not found
console.log([4, 6, 7, 9, 12].findIndex(isPrime)); // 2 (array[2] is 7)
```

### Using the third argument of callbackFn

The `array` argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses `filter()` to extract the positive values and then uses `findIndex()` to find the first element that is less than its neighbors.

```js
const numbers = [3, -1, 1, 4, 1, 5, 9, 2, 6];
const firstTrough = numbers
  .filter((num) => num > 0)
  .findIndex((num, idx, arr) => {
    // Without the arr argument, there's no way to easily access the
    // intermediate array without saving it to a variable.
    if (idx > 0 && num >= arr[idx - 1]) return false;
    if (idx < arr.length - 1 && num >= arr[idx + 1]) return false;
    return true;
  });
console.log(firstTrough); // 1
```

### Using findIndex() on sparse arrays

You can search for `undefined` in a sparse array and get the index of an empty slot.

```js
console.log([1, , 3].findIndex((x) => x === undefined)); // 1
```

### Calling findIndex() on non-array objects

The `findIndex()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`.

```js
const arrayLike = {
  length: 3,
  "-1": 0.1, // ignored by findIndex() since -1 < 0
  0: 2,
  1: 7.3,
  2: 4,
};
console.log(
  Array.prototype.findIndex.call(arrayLike, (x) => !Number.isInteger(x)),
); // 1
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.findindex |

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

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

See also
--------

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


Array.prototype.toString() - JavaScript

Array.prototype.toString()
==========================

 The **`toString()`** method of `Array` instances returns a string representing the
 specified array and its elements.

Try it
------

Syntax
------

```js
toString()
```

### Parameters

None.

### Return value

A string representing the elements of the array.

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

The `Array` object overrides the `toString` method of `Object`. The `toString` method of arrays calls `join()` internally, which joins the array and returns one string containing each array element separated by commas. If the `join` method is unavailable or is not a function, `Object.prototype.toString` is used instead, returning `[object Array]`.

```js
const arr = [];
arr.join = 1; // re-assign `join` with a non-function
console.log(arr.toString()); // [object Array]

console.log(Array.prototype.toString.call({ join: () => 1 })); // 1
```

JavaScript calls the `toString` method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation.

`Array.prototype.toString` recursively converts each element, including other arrays, to strings. Because the string returned by `Array.prototype.toString` does not have delimiters, nested arrays look like they are flattened.

```js
const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

console.log(matrix.toString()); // 1,2,3,4,5,6,7,8,9
```

When an array is cyclic (it contains an element that is itself), browsers avoid infinite recursion by ignoring the cyclic reference.

```js
const arr = [];
arr.push(1, [3, arr, 4], 2);
console.log(arr.toString()); // 1,3,,4,2
```

Examples
--------

### Using toString()

```js
const array1 = [1, 2, "a", "1a"];

console.log(array1.toString()); // "1,2,a,1a"
```

### Using toString() on sparse arrays

Following the behavior of `join()`, `toString()` treats empty slots the same as `undefined` and produces an extra separator:

```js
console.log([1, , 3].toString()); // '1,,3'
```

### Calling toString() on non-array objects

`toString()` is generic. It expects `this` to have a `join()` method; or, failing that, uses `Object.prototype.toString()` instead.

```js
console.log(Array.prototype.toString.call({ join: () => 1 }));
// 1; a number
console.log(Array.prototype.toString.call({ join: () => undefined }));
// undefined
console.log(Array.prototype.toString.call({ join: "not function" }));
// "[object Object]"
```

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

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

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

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

See also
--------

* Indexed collections guide
* `Array`
* `Array.prototype.join()`
* `Array.prototype.toLocaleString()`
* `TypedArray.prototype.toString()`
* `String.prototype.toString()`


Array.prototype.reduce() - JavaScript

Array.prototype.reduce()
========================

The **`reduce()`** method of `Array` instances executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

The first time that the callback is run there is no "return value of the previous calculation". If supplied, an initial value may be used in its place. Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0).

Try it
------

Syntax
------

```js
reduce(callbackFn)
reduce(callbackFn, initialValue)
```

### Parameters

`callbackFn`

A function to execute for each element in the array. Its return value becomes the value of the `accumulator` parameter on the next invocation of `callbackFn`. For the last invocation, the return value becomes the return value of `reduce()`. The function is called with the following arguments:

`accumulator`

The value resulting from the previous call to `callbackFn`. On the first call, its value is `initialValue` if the latter is specified; otherwise its value is `array[0]`.

`currentValue`

The value of the current element. On the first call, its value is `array[0]` if `initialValue` is specified; otherwise its value is `array[1]`.

`currentIndex`

The index position of `currentValue` in the array. On the first call, its value is `0` if `initialValue` is specified, otherwise `1`.

`array`

The array `reduce()` was called upon.

`initialValue` Optional

 A value to which `accumulator` is initialized the first time the callback is called.
 If `initialValue` is specified, `callbackFn` starts executing with the first value in the array as `currentValue`.
 If `initialValue` is *not* specified, `accumulator` is initialized to the first value in the array, and `callbackFn` starts executing with the second value in the array as `currentValue`. In this case, if the array is empty (so that there's no first value to return as `accumulator`), an error is thrown.

### Return value

The value that results from running the "reducer" callback function to completion over the entire array.

### Exceptions

`TypeError`

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

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

The `reduce()` method is an iterative method. It runs a "reducer" callback function over all elements in the array, in ascending-index order, and accumulates them into a single value. Every time, the return value of `callbackFn` is passed into `callbackFn` again on next invocation as `accumulator`. The final value of `accumulator` (which is the value returned from `callbackFn` on the final iteration of the array) becomes the return value of `reduce()`. Read the iterative methods section for more information about how these methods work in general.

`callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.

Unlike other iterative methods, `reduce()` does not accept a `thisArg` argument. `callbackFn` is always called with `undefined` as `this`, which gets substituted with `globalThis` if `callbackFn` is non-strict.

`reduce()` is a central concept in functional programming, where it's not possible to mutate any value, so in order to accumulate all values in an array, one must return a new accumulator value on every iteration. This convention propagates to JavaScript's `reduce()`: you should use spreading or other copying methods where possible to create new arrays and objects as the accumulator, rather than mutating the existing one. If you decided to mutate the accumulator instead of copying it, remember to still return the modified object in the callback, or the next iteration will receive undefined. However, note that copying the accumulator may in turn lead to increased memory usage and degraded performance — see When to not use reduce() for more details. In such cases, to avoid bad performance and unreadable code, it's better to use a simple `for` loop instead.

The `reduce()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

### Edge cases

If the array only has one element (regardless of position) and no `initialValue` is provided, or if `initialValue` is provided but the array is empty, the solo value will be returned *without* calling `callbackFn`.

If `initialValue` is provided and the array is not empty, then the reduce method will always invoke the callback function starting at index 0.

If `initialValue` is not provided then the reduce method will act differently for arrays with length larger than 1, equal to 1 and 0, as shown in the following example:

```js
const getMax = (a, b) => Math.max(a, b);

// callback is invoked for each element in the array starting at index 0
[1, 100].reduce(getMax, 50); // 100
[50].reduce(getMax, 10); // 50

// callback is invoked once for element at index 1
[1, 100].reduce(getMax); // 100

// callback is not invoked
[50].reduce(getMax); // 50
[].reduce(getMax, 1); // 1

[].reduce(getMax); // TypeError
```

Examples
--------

### How reduce() works without an initial value

The code below shows what happens if we call `reduce()` with an array and no initial value.

```js
const array = [15, 16, 17, 18, 19];

function reducer(accumulator, currentValue, index) {
  const returns = accumulator + currentValue;
  console.log(
    `accumulator: ${accumulator}, currentValue: ${currentValue}, index: ${index}, returns: ${returns}`,
  );
  return returns;
}

array.reduce(reducer);
```

The callback would be invoked four times, with the arguments and return values in each call being as follows:

|  | `accumulator` | `currentValue` | `index` | Return value |
| --- | --- | --- | --- | --- |
| First call | `15` | `16` | `1` | `31` |
| Second call | `31` | `17` | `2` | `48` |
| Third call | `48` | `18` | `3` | `66` |
| Fourth call | `66` | `19` | `4` | `85` |

The `array` parameter never changes through the process — it's always `[15, 16, 17, 18, 19]`. The value returned by `reduce()` would be that of the last callback invocation (`85`).

### How reduce() works with an initial value

Here we reduce the same array using the same algorithm, but with an `initialValue` of `10` passed as the second argument to `reduce()`:

```js
[15, 16, 17, 18, 19].reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  10,
);
```

The callback would be invoked five times, with the arguments and return values in each call being as follows:

|  | `accumulator` | `currentValue` | `index` | Return value |
| --- | --- | --- | --- | --- |
| First call | `10` | `15` | `0` | `25` |
| Second call | `25` | `16` | `1` | `41` |
| Third call | `41` | `17` | `2` | `58` |
| Fourth call | `58` | `18` | `3` | `76` |
| Fifth call | `76` | `19` | `4` | `95` |

The value returned by `reduce()` in this case would be `95`.

### Sum of values in an object array

 To sum up the values contained in an array of objects, you **must** supply
 an `initialValue`, so that each item passes through your function.

```js
const objects = [{ x: 1 }, { x: 2 }, { x: 3 }];
const sum = objects.reduce(
  (accumulator, currentValue) => accumulator + currentValue.x,
  0,
);

console.log(sum); // 6
```

### Function sequential piping

The `pipe` function takes a sequence of functions and returns a new function. When the new function is called with an argument, the sequence of functions are called in order, which each one receiving the return value of the previous function.

```js
const pipe =
  (...functions) =>
  (initialValue) =>
    functions.reduce((acc, fn) => fn(acc), initialValue);

// Building blocks to use for composition
const double = (x) => 2 \* x;
const triple = (x) => 3 \* x;
const quadruple = (x) => 4 \* x;

// Composed functions for multiplication of specific values
const multiply6 = pipe(double, triple);
const multiply9 = pipe(triple, triple);
const multiply16 = pipe(quadruple, quadruple);
const multiply24 = pipe(double, triple, quadruple);

// Usage
multiply6(6); // 36
multiply9(9); // 81
multiply16(16); // 256
multiply24(10); // 240
```

### Running promises in sequence

Promise sequencing is essentially function piping demonstrated in the previous section, except done asynchronously.

```js
// Compare this with pipe: fn(acc) is changed to acc.then(fn),
// and initialValue is ensured to be a promise
const asyncPipe =
  (...functions) =>
  (initialValue) =>
    functions.reduce((acc, fn) => acc.then(fn), Promise.resolve(initialValue));

// Building blocks to use for composition
const p1 = async (a) => a \* 5;
const p2 = async (a) => a \* 2;
// The composed functions can also return non-promises, because the values are
// all eventually wrapped in promises
const f3 = (a) => a \* 3;
const p4 = async (a) => a \* 4;

asyncPipe(p1, p2, f3, p4)(10).then(console.log); // 1200
```

`asyncPipe` can also be implemented using `async`/`await`, which better demonstrates its similarity with `pipe`:

```js
const asyncPipe =
  (...functions) =>
  (initialValue) =>
    functions.reduce(async (acc, fn) => fn(await acc), initialValue);
```

### Using reduce() with sparse arrays

`reduce()` skips missing elements in sparse arrays, but it does not skip `undefined` values.

```js
console.log([1, 2, , 4].reduce((a, b) => a + b)); // 7
console.log([1, 2, undefined, 4].reduce((a, b) => a + b)); // NaN
```

### Calling reduce() on non-array objects

The `reduce()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`.

```js
const arrayLike = {
  length: 3,
  0: 2,
  1: 3,
  2: 4,
  3: 99, // ignored by reduce() since length is 3
};
console.log(Array.prototype.reduce.call(arrayLike, (x, y) => x + y));
// 9
```

### When to not use reduce()

Multipurpose higher-order functions like `reduce()` can be powerful but sometimes difficult to understand, especially for less-experienced JavaScript developers. If code becomes clearer when using other array methods, developers must weigh the readability tradeoff against the other benefits of using `reduce()`.

Note that `reduce()` is always equivalent to a `for...of` loop, except that instead of mutating a variable in the upper scope, we now return the new value for each iteration:

```js
const val = array.reduce((acc, cur) => update(acc, cur), initialValue);

// Is equivalent to:
let val = initialValue;
for (const cur of array) {
  val = update(val, cur);
}
```

As previously stated, the reason why people may want to use `reduce()` is to mimic functional programming practices of immutable data. Therefore, developers who uphold the immutability of the accumulator often copy the entire accumulator for each iteration, like this:

```js
const names = ["Alice", "Bob", "Tiff", "Bruce", "Alice"];
const countedNames = names.reduce((allNames, name) => {
  const currCount = Object.hasOwn(allNames, name) ? allNames[name] : 0;
  return {
    ...allNames,
    [name]: currCount + 1,
  };
}, {});
```

This code is ill-performing, because each iteration has to copy the entire `allNames` object, which could be big, depending how many unique names there are. This code has worst-case `O(N^2)` performance, where `N` is the length of `names`.

A better alternative is to *mutate* the `allNames` object on each iteration. However, if `allNames` gets mutated anyway, you may want to convert the `reduce()` to a simple `for` loop instead, which is much clearer:

```js
const names = ["Alice", "Bob", "Tiff", "Bruce", "Alice"];
const countedNames = names.reduce((allNames, name) => {
  const currCount = allNames[name] ?? 0;
  allNames[name] = currCount + 1;
  // return allNames, otherwise the next iteration receives undefined
  return allNames;
}, Object.create(null));
```

```js
const names = ["Alice", "Bob", "Tiff", "Bruce", "Alice"];
const countedNames = Object.create(null);
for (const name of names) {
  const currCount = countedNames[name] ?? 0;
  countedNames[name] = currCount + 1;
}
```

Therefore, if your accumulator is an array or an object and you are copying the array or object on each iteration, you may accidentally introduce quadratic complexity into your code, causing performance to quickly degrade on large data. This has happened in real-world code — see for example Making Tanstack Table 1000x faster with a 1 line change.

Some of the acceptable use cases of `reduce()` are given above (most notably, summing an array, promise sequencing, and function piping). There are other cases where better alternatives than `reduce()` exist.

* Flattening an array of arrays. Use `flat()` instead.

```js
const flattened = array.reduce((acc, cur) => acc.concat(cur), []);
```

```js
const flattened = array.flat();
```

* Grouping objects by a property. Use `Object.groupBy()` instead.

```js
const groups = array.reduce((acc, obj) => {
  const key = obj.name;
  const curGroup = acc[key] ?? [];
  return { ...acc, [key]: [...curGroup, obj] };
}, {});
```

```js
const groups = Object.groupBy(array, (obj) => obj.name);
```

* Concatenating arrays contained in an array of objects. Use `flatMap()` instead.

```js
const friends = [
  { name: "Anna", books: ["Bible", "Harry Potter"] },
  { name: "Bob", books: ["War and peace", "Romeo and Juliet"] },
  { name: "Alice", books: ["The Lord of the Rings", "The Shining"] },
];
const allBooks = friends.reduce((acc, cur) => [...acc, ...cur.books], []);
```

```js
const allBooks = friends.flatMap((person) => person.books);
```

* Removing duplicate items in an array. Use `Set` and `Array.from()` instead.

```js
const uniqArray = array.reduce(
  (acc, cur) => (acc.includes(cur) ? acc : [...acc, cur]),
  [],
);
```

```js
const uniqArray = Array.from(new Set(array));
```

* Eliminating or adding elements in an array. Use `flatMap()` instead.

```js
// Takes an array of numbers and splits perfect squares into its square roots
const roots = array.reduce((acc, cur) => {
  if (cur < 0) return acc;
  const root = Math.sqrt(cur);
  if (Number.isInteger(root)) return [...acc, root, root];
  return [...acc, cur];
}, []);
```

```js
const roots = array.flatMap((val) => {
  if (val < 0) return [];
  const root = Math.sqrt(val);
  if (Number.isInteger(root)) return [root, root];
  return [val];
});
```

If you are only eliminating elements from an array, you also can use `filter()`.
* Searching for elements or testing if elements satisfy a condition. Use `find()` and `findIndex()`, or `some()` and `every()` instead. These methods have the additional benefit that they return as soon as the result is certain, without iterating the entire array.

```js
const allEven = array.reduce((acc, cur) => acc && cur % 2 === 0, true);
```

```js
const allEven = array.every((val) => val % 2 === 0);
```

In cases where `reduce()` is the best choice, documentation and semantic variable naming can help mitigate readability drawbacks.

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.reduce |

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

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

See also
--------

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


Array.prototype.map() - JavaScript

Array.prototype.map()
=====================

 The **`map()`** method of `Array` instances creates
 a new array populated with the results of calling a provided function on
 every element in the calling array.

Try it
------

Syntax
------

```js
map(callbackFn)
map(callbackFn, thisArg)
```

### Parameters

`callbackFn`

A function to execute for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments:

`element`

The current element being processed in the array.

`index`

The index of the current element being processed in the array.

`array`

The array `map()` was called upon.

`thisArg` Optional

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

### Return value

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

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

The `map()` method is an iterative method. It calls a provided `callbackFn` function once for each element in an array and constructs a new array from the results. Read the iterative methods section for more information about how these methods work in general.

`callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.

The `map()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

Since `map` builds a new array, calling it without using the returned array is an anti-pattern; use `forEach` or `for...of` instead.

Examples
--------

### Mapping an array of numbers to an array of square roots

The following code takes an array of numbers and creates a new array containing the square roots of the numbers in the first array.

```js
const numbers = [1, 4, 9];
const roots = numbers.map((num) => Math.sqrt(num));

// roots is now [1, 2, 3]
// numbers is still [1, 4, 9]
```

### Using map to reformat objects in an array

The following code takes an array of objects and creates a new array containing the newly reformatted objects.

```js
const kvArray = [
  { key: 1, value: 10 },
  { key: 2, value: 20 },
  { key: 3, value: 30 },
];

const reformattedArray = kvArray.map(({ key, value }) => ({ [key]: value }));

console.log(reformattedArray); // [{ 1: 10 }, { 2: 20 }, { 3: 30 }]
console.log(kvArray);
// [
// { key: 1, value: 10 },
// { key: 2, value: 20 },
// { key: 3, value: 30 }
// ]
```

### Using parseInt() with map()

It is common to use the callback with one argument (the element being traversed). Certain functions are also commonly used with one argument, even though they take additional optional arguments. These habits may lead to confusing behaviors. Consider:

```js
["1", "2", "3"].map(parseInt);
```

While one might expect `[1, 2, 3]`, the actual result is `[1, NaN, NaN]`.

`parseInt` is often used with one argument, but takes two. The first is an expression and the second is the radix to the callback function, `Array.prototype.map` passes 3 arguments: the element, the index, and the array. The third argument is ignored by `parseInt` — but *not* the second one! This is the source of possible confusion.

Here is a concise example of the iteration steps:

```js
/\* first iteration (index is 0): \*/ parseInt("1", 0); // 1
/\* second iteration (index is 1): \*/ parseInt("2", 1); // NaN
/\* third iteration (index is 2): \*/ parseInt("3", 2); // NaN
```

To solve this, define another function that only takes one argument:

```js
["1", "2", "3"].map((str) => parseInt(str, 10)); // [1, 2, 3]
```

You can also use the `Number` function, which only takes one argument:

```js
["1", "2", "3"].map(Number); // [1, 2, 3]

// But unlike parseInt(), Number() will also return a float or (resolved) exponential notation:
["1.1", "2.2e2", "3e300"].map(Number); // [1.1, 220, 3e+300]

// For comparison, if we use parseInt() on the array above:
["1.1", "2.2e2", "3e300"].map((str) => parseInt(str, 10)); // [1, 2, 3]
```

See A JavaScript optional argument hazard by Allen Wirfs-Brock for more discussions.

### Mapped array contains undefined

When `undefined` or nothing is returned, the resulting array contains `undefined`. If you want to delete the element instead, chain a `filter()` method, or use the `flatMap()` method and return an empty array to signify deletion.

```js
const numbers = [1, 2, 3, 4];
const filteredNumbers = numbers.map((num, index) => {
  if (index < 3) {
    return num;
  }
});

// index goes from 0, so the filterNumbers are 1,2,3 and undefined.
// filteredNumbers is [1, 2, 3, undefined]
// numbers is still [1, 2, 3, 4]
```

### Side-effectful mapping

The callback can have side effects.

```js
const cart = [5, 15, 25];
let total = 0;
const withTax = cart.map((cost) => {
  total += cost;
  return cost \* 1.2;
});
console.log(withTax); // [6, 18, 30]
console.log(total); // 45
```

This is not recommended, because copying methods are best used with pure functions. In this case, we can choose to iterate the array twice.

```js
const cart = [5, 15, 25];
const total = cart.reduce((acc, cost) => acc + cost, 0);
const withTax = cart.map((cost) => cost \* 1.2);
```

Sometimes this pattern goes to its extreme and the *only* useful thing that `map()` does is causing side effects.

```js
const products = [
  { name: "sports car" },
  { name: "laptop" },
  { name: "phone" },
];

products.map((product) => {
  product.price = 100;
});
```

As mentioned previously, this is an anti-pattern. If you don't use the return value of `map()`, use `forEach()` or a `for...of` loop instead.

```js
products.forEach((product) => {
  product.price = 100;
});
```

Or, if you want to create a new array instead:

```js
const productsWithPrice = products.map((product) => {
  return { ...product, price: 100 };
});
```

### Using the third argument of callbackFn

The `array` argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses `filter()` to extract the positive values and then uses `map()` to create a new array where each element is the average of its neighbors and itself.

```js
const numbers = [3, -1, 1, 4, 1, 5, 9, 2, 6];
const averaged = numbers
  .filter((num) => num > 0)
  .map((num, idx, arr) => {
    // Without the arr argument, there's no way to easily access the
    // intermediate array without saving it to a variable.
    const prev = arr[idx - 1];
    const next = arr[idx + 1];
    let count = 1;
    let total = num;
    if (prev !== undefined) {
      count++;
      total += prev;
    }
    if (next !== undefined) {
      count++;
      total += next;
    }
    const average = total / count;
    // Keep two decimal places
    return Math.round(average \* 100) / 100;
  });
console.log(averaged); // [2, 2.67, 2, 3.33, 5, 5.33, 5.67, 4]
```

The `array` argument is *not* the array that is being built — there is no way to access the array being built from the callback function.

### Using map() on sparse arrays

A sparse array remains sparse after `map()`. The indices of empty slots are still empty in the returned array, and the callback function won't be called on them.

```js
console.log(
  [1, , 3].map((x, index) => {
    console.log(`Visit ${index}`);
    return x \* 2;
  }),
);
// Visit 0
// Visit 2
// [2, empty, 6]
```

### Calling map() on non-array objects

The `map()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`.

```js
const arrayLike = {
  length: 3,
  0: 2,
  1: 3,
  2: 4,
  3: 5, // ignored by map() since length is 3
};
console.log(Array.prototype.map.call(arrayLike, (x) => x \*\* 2));
// [ 4, 9, 16 ]
```

This example shows how to iterate through a collection of objects collected by `querySelectorAll`. This is because `querySelectorAll` returns a `NodeList` (which is a collection of objects). In this case, we return all the selected `option`s' values on the screen:

```js
const elems = document.querySelectorAll("select option:checked");
const values = Array.prototype.map.call(elems, ({ value }) => value);
```

You can also use `Array.from()` to transform `elems` to an array, and then access the `map()` method.

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

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

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

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

See also
--------

* Polyfill of `Array.prototype.map` in `core-js`
* Indexed collections guide
* `Array`
* `Array.prototype.forEach()`
* `Array.from()`
* `TypedArray.prototype.map()`
* `Map`


Array.prototype.lastIndexOf() - JavaScript

Array.prototype.lastIndexOf()
=============================

 The **`lastIndexOf()`** method of `Array` instances returns the last index at which
 a given element can be found in the array, or -1 if it is not present. The array is
 searched backwards, starting at `fromIndex`.

Try it
------

Syntax
------

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

### Parameters

`searchElement`

Element to locate in the array.

`fromIndex` Optional

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

* Negative index counts back from the end of the array — if `fromIndex < 0`, `fromIndex + array.length` is used.
* If `fromIndex < -array.length`, the array is not searched and `-1` is returned. You can think of it conceptually as starting at a nonexistent position before the beginning of the array and going backwards from there. There are no array elements on the way, so `searchElement` is never found.
* If `fromIndex >= array.length` or `fromIndex` is omitted, `array.length - 1` is used, causing the entire array to be searched. You can think of it conceptually as starting at a nonexistent position beyond the end of the array and going backwards from there. It eventually reaches the real end position of the array, at which point it starts searching backwards through the actual array elements.

### Return value

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

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

The `lastIndexOf()` method compares `searchElement` to elements of the array using strict equality (the same algorithm used by the `===` operator). `NaN` values are never compared as equal, so `lastIndexOf()` always returns `-1` when `searchElement` is `NaN`.

The `lastIndexOf()` method skips empty slots in sparse arrays.

The `lastIndexOf()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

Examples
--------

### Using lastIndexOf()

The following example uses `lastIndexOf()` to locate values in an array.

```js
const numbers = [2, 5, 9, 2];
numbers.lastIndexOf(2); // 3
numbers.lastIndexOf(7); // -1
numbers.lastIndexOf(2, 3); // 3
numbers.lastIndexOf(2, 2); // 0
numbers.lastIndexOf(2, -2); // 0
numbers.lastIndexOf(2, -1); // 3
```

You cannot use `lastIndexOf()` to search for `NaN`.

```js
const array = [NaN];
array.lastIndexOf(NaN); // -1
```

### Finding all the occurrences of an element

 The following example uses `lastIndexOf` to find all the indices of an
 element in a given array, using `push()` to add them
 to another array as they are found.

```js
const indices = [];
const array = ["a", "b", "a", "c", "a", "d"];
const element = "a";
let idx = array.lastIndexOf(element);
while (idx !== -1) {
  indices.push(idx);
  idx = idx > 0 ? array.lastIndexOf(element, idx - 1) : -1;
}

console.log(indices);
// [4, 2, 0]
```

 Note that we have to handle the case `idx === 0` separately here because the
 element will always be found regardless of the `fromIndex` parameter if it is
 the first element of the array. This is different from the
 `indexOf()` method.

### Using lastIndexOf() on sparse arrays

You cannot use `lastIndexOf()` to search for empty slots in sparse arrays.

```js
console.log([1, , 3].lastIndexOf(undefined)); // -1
```

### Calling lastIndexOf() on non-array objects

The `lastIndexOf()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`.

```js
const arrayLike = {
  length: 3,
  0: 2,
  1: 3,
  2: 2,
  3: 5, // ignored by lastIndexOf() since length is 3
};
console.log(Array.prototype.lastIndexOf.call(arrayLike, 2));
// 2
console.log(Array.prototype.lastIndexOf.call(arrayLike, 5));
// -1
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.lastindexof |

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

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

See also
--------

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


Array.prototype.at() - JavaScript

Array.prototype.at()
====================

Baseline 2022
-------------

Newly availableSince March 2022, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

* Learn more
* See full compatibility
* Report feedback
The **`at()`** method of `Array` 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 array.

Try it
------

Syntax
------

```js
at(index)
```

### Parameters

`index`

Zero-based index of the array element to be returned, converted to an integer. Negative index counts back from the end of the array — if `index < 0`, `index + array.length` is accessed.

### Return value

The element in the array matching the given index. Always returns `undefined` if `index < -array.length` or `index >= array.length` without attempting to access the corresponding property.

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

The `at()` method is equivalent to the bracket notation when `index` is non-negative. For example, `array[0]` and `array.at(0)` both return the first item. However, when counting elements from the end of the array, you cannot use `array[-1]` like you may in Python or R, because all values inside the square brackets are treated literally as string properties, so you will end up reading `array["-1"]`, which is just a normal string property instead of an array index.

The usual practice is to access `length` and calculate the index from that — for example, `array[array.length - 1]`. The `at()` method allows relative indexing, so this can be shortened to `array.at(-1)`.

By combining `at()` with `with()`, you can both read and write (respectively) an array using negative indices.

The `at()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

Examples
--------

### Return the last value of an array

The following example provides a function which returns the last element found in a specified array.

```js
// Our array with items
const cart = ["apple", "banana", "pear"];

// A function which returns the last item of a given array
function returnLast(arr) {
  return arr.at(-1);
}

// Get the last item of our array 'cart'
const item1 = returnLast(cart);
console.log(item1); // 'pear'

// Add an item to our 'cart' array
cart.push("orange");
const item2 = returnLast(cart);
console.log(item2); // 'orange'
```

### Comparing methods

This example compares different ways to select the penultimate (last but one) item of an `Array`. While all the methods shown below are valid, this example highlights the succinctness and readability of the `at()` method.

```js
// Our array with items
const colors = ["red", "green", "blue"];

// Using length property
const lengthWay = colors[colors.length - 2];
console.log(lengthWay); // 'green'

// Using slice() method. Note an array is returned
const sliceWay = colors.slice(-2, -1);
console.log(sliceWay[0]); // 'green'

// Using at() method
const atWay = colors.at(-2);
console.log(atWay); // 'green'
```

### Calling at() on non-array objects

The `at()` method reads the `length` property of `this` and calculates the index to access.

```js
const arrayLike = {
  length: 2,
  0: "a",
  1: "b",
  2: "c", // ignored by at() since length is 2
};
console.log(Array.prototype.at.call(arrayLike, 0)); // "a"
console.log(Array.prototype.at.call(arrayLike, 2)); // undefined
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.at |

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

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

See also
--------

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


Array.prototype.concat() - JavaScript

Array.prototype.concat()
========================

 The **`concat()`** method of `Array` instances is used to merge two or more arrays.
 This method does not change the existing arrays, but instead returns a new array.

Try it
------

Syntax
------

```js
concat()
concat(value1)
concat(value1, value2)
concat(value1, value2, /\* …, \*/ valueN)
```

### Parameters

`value1`, …, `valueN` Optional

 Arrays and/or values to concatenate into a new array. If all
 `valueN` parameters are omitted, `concat` returns a
 shallow copy of the existing array on which it is called. See the description below
 for more details.

### Return value

A new `Array` instance.

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

The `concat` method creates a new array. The array will first be populated by the elements in the object on which it is called. Then, for each argument, its value will be concatenated into the array — for normal objects or primitives, the argument itself will become an element of the final array; for arrays or array-like objects with the property `Symbol.isConcatSpreadable` set to a truthy value, each element of the argument will be independently added to the final array. The `concat` method does not recurse into nested array arguments.

The `concat()` method is a copying method. It does not alter `this` or any of the arrays provided as arguments but instead returns a shallow copy that contains the same elements as the ones from the original arrays.

The `concat()` method preserves empty slots if any of the source arrays is sparse.

The `concat()` method is generic. The `this` value is treated in the same way as the other arguments (except it will be converted to an object first), which means plain objects will be directly prepended to the resulting array, while array-like objects with truthy `@@isConcatSpreadable` will be spread into the resulting array.

Examples
--------

### Concatenating two arrays

The following code concatenates two arrays:

```js
const letters = ["a", "b", "c"];
const numbers = [1, 2, 3];

const alphaNumeric = letters.concat(numbers);
console.log(alphaNumeric);
// results in ['a', 'b', 'c', 1, 2, 3]
```

### Concatenating three arrays

The following code concatenates three arrays:

```js
const num1 = [1, 2, 3];
const num2 = [4, 5, 6];
const num3 = [7, 8, 9];

const numbers = num1.concat(num2, num3);

console.log(numbers);
// results in [1, 2, 3, 4, 5, 6, 7, 8, 9]
```

### Concatenating values to an array

The following code concatenates three values to an array:

```js
const letters = ["a", "b", "c"];

const alphaNumeric = letters.concat(1, [2, 3]);

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

### Concatenating nested arrays

The following code concatenates nested arrays and demonstrates retention of references:

```js
const num1 = [[1]];
const num2 = [2, [3]];

const numbers = num1.concat(num2);

console.log(numbers);
// results in [[1], 2, [3]]

// modify the first element of num1
num1[0].push(4);

console.log(numbers);
// results in [[1, 4], 2, [3]]
```

### Concatenating array-like objects with Symbol.isConcatSpreadable

`concat` does not treat all array-like objects as arrays by default — only if `Symbol.isConcatSpreadable` is set to a truthy value (e.g. `true`).

```js
const obj1 = { 0: 1, 1: 2, 2: 3, length: 3 };
const obj2 = { 0: 1, 1: 2, 2: 3, length: 3, [Symbol.isConcatSpreadable]: true };
console.log([0].concat(obj1, obj2));
// [ 0, { '0': 1, '1': 2, '2': 3, length: 3 }, 1, 2, 3 ]
```

### Using concat() on sparse arrays

If any of the source arrays is sparse, the resulting array will also be sparse:

```js
console.log([1, , 3].concat([4, 5])); // [1, empty, 3, 4, 5]
console.log([1, 2].concat([3, , 5])); // [1, 2, 3, empty, 5]
```

### Calling concat() on non-array objects

If the `this` value is not an array, it is converted to an object and then treated in the same way as the arguments for `concat()`. In this case the return value is always a plain new array.

```js
console.log(Array.prototype.concat.call({}, 1, 2, 3)); // [{}, 1, 2, 3]
console.log(Array.prototype.concat.call(1, 2, 3)); // [ [Number: 1], 2, 3 ]
const arrayLike = {
  [Symbol.isConcatSpreadable]: true,
  length: 2,
  0: 1,
  1: 2,
  2: 99, // ignored by concat() since length is 2
};
console.log(Array.prototype.concat.call(arrayLike, 3, 4)); // [1, 2, 3, 4]
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.concat |

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

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

See also
--------

* Polyfill of `Array.prototype.concat` in `core-js` with fixes and implementation of modern behavior like `Symbol.isConcatSpreadable` support
* Indexed collections guide
* `Array`
* `Array.prototype.push()`
* `Array.prototype.unshift()`
* `Array.prototype.splice()`
* `String.prototype.concat()`
* `Symbol.isConcatSpreadable`


Array.prototype.toSorted() - JavaScript

Array.prototype.toSorted()
==========================

The **`toSorted()`** method of `Array` instances is the copying version of the `sort()` method. It returns a new array with the elements sorted in ascending order.

Syntax
------

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

### Parameters

`compareFn` Optional

Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value.

`a`

The first element for comparison.

`b`

The second element for comparison.

### Return value

A new array with the elements sorted in ascending order.

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

See `sort()` for more information on the `compareFn` parameter.

When used on sparse arrays, the `toSorted()` method iterates empty slots as if they have the value `undefined`.

The `toSorted()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

Examples
--------

### Sorting an array

```js
const months = ["Mar", "Jan", "Feb", "Dec"];
const sortedMonths = months.toSorted();
console.log(sortedMonths); // ['Dec', 'Feb', 'Jan', 'Mar']
console.log(months); // ['Mar', 'Jan', 'Feb', 'Dec']

const values = [1, 10, 21, 2];
const sortedValues = values.toSorted((a, b) => a - b);
console.log(sortedValues); // [1, 2, 10, 21]
console.log(values); // [1, 10, 21, 2]
```

For more usage examples, see `sort()`.

### Using toSorted() on sparse arrays

Empty slots are sorted as if they have the value `undefined`. They are always sorted to the end of the array and `compareFn` is not called for them.

```js
console.log(["a", "c", , "b"].toSorted()); // ['a', 'b', 'c', undefined]
console.log([, undefined, "a", "b"].toSorted()); // ["a", "b", undefined, undefined]
```

### Calling toSorted() on non-array objects

The `toSorted()` method reads the `length` property of `this`. It then collects all existing integer-keyed properties in the range of `0` to `length - 1`, sorts them, and writes them into a new array.

```js
const arrayLike = {
  length: 3,
  unrelated: "foo",
  0: 5,
  2: 4,
  3: 3, // ignored by toSorted() since length is 3
};
console.log(Array.prototype.toSorted.call(arrayLike));
// [4, 5, undefined]
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.tosorted |

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

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

See also
--------

* Polyfill of `Array.prototype.toSorted` in `core-js`
* Indexed collections guide
* `Array.prototype.sort()`
* `Array.prototype.toReversed()`
* `Array.prototype.toSpliced()`
* `Array.prototype.with()`
* `TypedArray.prototype.toSorted()`


Array.prototype.toReversed() - JavaScript

Array.prototype.toReversed()
============================

The **`toReversed()`** method of `Array` instances is the copying counterpart of the `reverse()` method. It returns a new array with the elements in reversed order.

Syntax
------

```js
toReversed()
```

### Parameters

None.

### Return value

A new array containing the elements in reversed order.

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

The `toReversed()` method transposes the elements of the calling array object in reverse order and returns a new array.

When used on sparse arrays, the `toReversed()` method iterates empty slots as if they have the value `undefined`.

The `toReversed()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

Examples
--------

### Reversing the elements in an array

The following example creates an array `items`, containing three elements, then creates a new array that's the reverse of `items`. The `items` array remains unchanged.

```js
const items = [1, 2, 3];
console.log(items); // [1, 2, 3]

const reversedItems = items.toReversed();
console.log(reversedItems); // [3, 2, 1]
console.log(items); // [1, 2, 3]
```

### Using toReversed() on sparse arrays

The return value of `toReversed()` is never sparse. Empty slots become `undefined` in the returned array.

```js
console.log([1, , 3].toReversed()); // [3, undefined, 1]
console.log([1, , 3, 4].toReversed()); // [4, 3, undefined, 1]
```

### Calling toReversed() on non-array objects

The `toReversed()` method reads the `length` property of `this`. It then visits each property having an integer key between `length - 1` and `0` in descending order, adding the value of the current property to the end of the array to be returned.

```js
const arrayLike = {
  length: 3,
  unrelated: "foo",
  2: 4,
};
console.log(Array.prototype.toReversed.call(arrayLike));
// [4, undefined, undefined]
// The '0' and '1' indices are not present so they become undefined
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.toreversed |

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

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

See also
--------

* Polyfill of `Array.prototype.toReversed` in `core-js`
* Indexed collections guide
* `Array.prototype.reverse()`
* `Array.prototype.toSorted()`
* `Array.prototype.toSpliced()`
* `Array.prototype.with()`
* `TypedArray.prototype.toReversed()`


Array.isArray() - JavaScript

Array.isArray()
===============

The **`Array.isArray()`** static method determines whether the passed value is an `Array`.

Try it
------

Syntax
------

```js
Array.isArray(value)
```

### Parameters

`value`

The value to be checked.

### Return value

`true` if `value` is an `Array`; otherwise, `false`. `false` is always returned if `value` is a `TypedArray` instance.

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

`Array.isArray()` checks if the passed value is an `Array`. It does not check the value's prototype chain, nor does it rely on the `Array` constructor it is attached to. It returns `true` for any value that was created using the array literal syntax or the `Array` constructor. This makes it safe to use with cross-realm objects, where the identity of the `Array` constructor is different and would therefore cause `instanceof Array` to fail.

See the article "Determining with absolute accuracy whether or not a JavaScript object is an array" for more details.

`Array.isArray()` also rejects objects with `Array.prototype` in its prototype chain but aren't actual arrays, which `instanceof Array` would accept.

Examples
--------

### Using Array.isArray()

```js
// all following calls return true
Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
Array.isArray(new Array("a", "b", "c", "d"));
Array.isArray(new Array(3));
// Little known fact: Array.prototype itself is an array:
Array.isArray(Array.prototype);

// all following calls return false
Array.isArray();
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
Array.isArray(17);
Array.isArray("Array");
Array.isArray(true);
Array.isArray(false);
Array.isArray(new Uint8Array(32));
// This is not an array, because it was not created using the
// array literal syntax or the Array constructor
Array.isArray({ \_\_proto\_\_: Array.prototype });
```

### instanceof vs. Array.isArray()

When checking for `Array` instance, `Array.isArray()` is preferred over `instanceof` because it works across realms.

```js
const iframe = document.createElement("iframe");
document.body.appendChild(iframe);
const xArray = window.frames[window.frames.length - 1].Array;
const arr = new xArray(1, 2, 3); // [1, 2, 3]

// Correctly checking for Array
Array.isArray(arr); // true
// The prototype of arr is xArray.prototype, which is a
// different object from Array.prototype
arr instanceof Array; // false
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.isarray |

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

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

See also
--------

* Polyfill of `Array.isArray` in `core-js`
* Indexed collections guide
* `Array`


Array.prototype.entries() - JavaScript

Array.prototype.entries()
=========================

The **`entries()`** method of `Array` instances returns a new *array iterator* object that contains the key/value pairs for each index in the array.

Try it
------

Syntax
------

```js
entries()
```

### Parameters

None.

### Return value

A new iterable iterator object.

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

When used on sparse arrays, the `entries()` method iterates empty slots as if they have the value `undefined`.

The `entries()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties.

Examples
--------

### Iterating with index and element

```js
const a = ["a", "b", "c"];

for (const [index, element] of a.entries()) {
  console.log(index, element);
}

// 0 'a'
// 1 'b'
// 2 'c'
```

### Using a for...of loop

```js
const array = ["a", "b", "c"];
const arrayEntries = array.entries();

for (const element of arrayEntries) {
  console.log(element);
}

// [0, 'a']
// [1, 'b']
// [2, 'c']
```

### Iterating sparse arrays

`entries()` will visit empty slots as if they are `undefined`.

```js
for (const element of [, "a"].entries()) {
  console.log(element);
}
// [0, undefined]
// [1, 'a']
```

### Calling entries() on non-array objects

The `entries()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`.

```js
const arrayLike = {
  length: 3,
  0: "a",
  1: "b",
  2: "c",
  3: "d", // ignored by entries() since length is 3
};
for (const entry of Array.prototype.entries.call(arrayLike)) {
  console.log(entry);
}
// [ 0, 'a' ]
// [ 1, 'b' ]
// [ 2, 'c' ]
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.entries |

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

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

See also
--------

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


Array.prototype.flatMap() - JavaScript

Array.prototype.flatMap()
=========================

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

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

* Learn more
* See full compatibility
* Report feedback
The **`flatMap()`** method of `Array` instances returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a `map()` followed by a `flat()` of depth 1 (`arr.map(...args).flat()`), but slightly more efficient than calling those two methods separately.

Try it
------

Syntax
------

```js
flatMap(callbackFn)
flatMap(callbackFn, thisArg)
```

### Parameters

`callbackFn`

A function to execute for each element in the array. It should return an array containing new elements of the new array, or a single non-array value to be added to the new array. The function is called with the following arguments:

`element`

The current element being processed in the array.

`index`

The index of the current element being processed in the array.

`array`

The array `flatMap()` was called upon.

`thisArg` Optional

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

### Return value

 A new array with each element being the result of the callback function and flattened
 by a depth of 1.

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

The `flatMap()` method is an iterative method. See `Array.prototype.map()` for a detailed description of the callback function. The `flatMap()` method is identical to `map(callbackFn, thisArg)` followed by `flat(1)` — for each element, it produces an array of new elements, and concatenates the resulting arrays together to form a new array. Read the iterative methods section for more information about how these methods work in general.

The `flatMap()` method is generic. It only expects the `this` value to have a `length` property and integer-keyed properties. However, the value returned from `callbackFn` must be an array if it is to be flattened.

### Alternative

#### Pre-allocate and explicitly iterate

```js
const arr = [1, 2, 3, 4];

arr.flatMap((x) => [x, x \* 2]);
// is equivalent to
const n = arr.length;
const acc = new Array(n \* 2);
for (let i = 0; i < n; i++) {
  const x = arr[i];
  acc[i \* 2] = x;
  acc[i \* 2 + 1] = x \* 2;
}
// [1, 2, 2, 4, 3, 6, 4, 8]
```

 Note that in this particular case the `flatMap` approach is slower than the
 for-loop approach — due to the creation of temporary arrays that must be
 garbage collected, as well as the return array not needing to be frequently
 resized. However, `flatMap` may still be the correct solution in cases where
 its flexibility and readability are desired.

Examples
--------

### map() and flatMap()

```js
const arr1 = [1, 2, 3, 4];

arr1.map((x) => [x \* 2]);
// [[2], [4], [6], [8]]

arr1.flatMap((x) => [x \* 2]);
// [2, 4, 6, 8]

// only one level is flattened
arr1.flatMap((x) => [[x \* 2]]);
// [[2], [4], [6], [8]]
```

 While the above could have been achieved by using map itself, here is an example that
 better showcases the use of `flatMap()`.

Let's generate a list of words from a list of sentences.

```js
const arr1 = ["it's Sunny in", "", "California"];

arr1.map((x) => x.split(" "));
// [["it's","Sunny","in"],[""],["California"]]

arr1.flatMap((x) => x.split(" "));
// ["it's","Sunny","in", "", "California"]
```

Notice, the output list length can be different from the input list length.

### For adding and removing items during a map()

`flatMap` can be used as a way to add and remove items (modify the number of
 items) during a `map`. In other words, it allows you to map *many items to
many items* (by handling each input item separately), rather than always
 *one-to-one*. In this sense, it works like the opposite of filter.
 Return a 1-element array to keep the item, a multiple-element array to add items, or a
 0-element array to remove the item.

```js
// Let's say we want to remove all the negative numbers
// and split the odd numbers into an even number and a 1
const a = [5, 4, -3, 20, 17, -33, -4, 18];
// |\ \ x | | \ x x |
// [4,1, 4, 20, 16, 1, 18]

const result = a.flatMap((n) => {
  if (n < 0) {
    return [];
  }
  return n % 2 === 0 ? [n] : [n - 1, 1];
});
console.log(result); // [4, 1, 4, 20, 16, 1, 18]
```

### Using the third argument of callbackFn

The `array` argument is useful if you want to access another element in the array, especially when you don't have an existing variable that refers to the array. The following example first uses `filter()` to extract operational stations and then uses `flatMap()` to create a new array where each element contains a station and its next station. On the last station, it returns an empty array to exclude it from the final array.

```js
const stations = ["New Haven", "West Haven", "Milford (closed)", "Stratford"];
const line = stations
  .filter((name) => !name.endsWith("(closed)"))
  .flatMap((name, idx, arr) => {
    // Without the arr argument, there's no way to easily access the
    // intermediate array without saving it to a variable.
    if (idx === arr.length - 1) return []; // last station has no next station
    return [`${name} - ${arr[idx + 1]}`];
  });
console.log(line); // ['New Haven - West Haven', 'West Haven - Stratford']
```

The `array` argument is *not* the array that is being built — there is no way to access the array being built from the callback function.

### Using flatMap() on sparse arrays

The `callbackFn` won't be called for empty slots in the source array because `map()` doesn't, while `flat()` ignores empty slots in the returned arrays.

```js
console.log([1, 2, , 4, 5].flatMap((x) => [x, x \* 2])); // [1, 2, 2, 4, 4, 8, 5, 10]
console.log([1, 2, 3, 4].flatMap((x) => [, x \* 2])); // [2, 4, 6, 8]
```

### Calling flatMap() on non-array objects

The `flatMap()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`. If the return value of the callback function is not an array, it is always directly appended to the result array.

```js
const arrayLike = {
  length: 3,
  0: 1,
  1: 2,
  2: 3,
  3: 4, // ignored by flatMap() since length is 3
};
console.log(Array.prototype.flatMap.call(arrayLike, (x) => [x, x \* 2]));
// [1, 2, 2, 4, 3, 6]

// Array-like objects returned from the callback won't be flattened
console.log(
  Array.prototype.flatMap.call(arrayLike, (x) => ({
    length: 1,
    0: x,
  })),
);
// [ { '0': 1, length: 1 }, { '0': 2, length: 1 }, { '0': 3, length: 1 } ]
```

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

| Specification |
| --- |
| ECMAScript Language Specification # sec-array.prototype.flatmap |

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

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

See also
--------

* Polyfill of `Array.prototype.flatMap` in `core-js`
* Indexed collections guide
* `Array`
* `Array.prototype.concat()`
* `Array.prototype.flat()`
* `Array.prototype.map()`
* `Array.prototype.reduce()`