Array
The
Array
object, as with arrays in other programming languages, enables
storing a collection of multiple items under a single variable name
, and has members for
performing common array operations
.
Description
In JavaScript, arrays aren't
primitives
but are instead
Array
objects with the following core characteristics:
0
, the second is at index
1
, and so on — and the last element is at the value of the array's
length
property minus
1
.
Array indices
Array
objects cannot use arbitrary strings as element indexes (as in an
associative array
) but must use nonnegative integers (or their respective string form). Setting or accessing via non-integers will not set or retrieve an element from the array list itself, but will set or access a variable associated with that array's
object property collection
. The array's object properties and list of array elements are separate, and the array's
traversal and mutation operations
cannot be applied to these named properties.
Array elements are object properties in the same way that
toString
is a property (to be specific, however,
toString()
is a method). Nevertheless, trying to access an element of an array as follows throws a syntax error because the property name is not valid:
console.log(arr.0);
// a syntax error
JavaScript syntax requires properties beginning with a digit to be accessed using bracket notation instead of dot notation. It's also possible to quote the array indices (e.g., years['2'] instead of years[2]), although usually not necessary.
The 2 in years[2] is coerced into a string by the JavaScript engine through an implicit toString conversion. As a result, '2' and '02' would refer to two different slots on the years object, and the following example could be true:
console.log(years["2"] !== years["02"]);
Only years['2'] is an actual array index. years['02'] is an arbitrary string property that will not be visited in array iteration.
Relationship between length and numerical properties
Relationship between length and numerical properties
A JavaScript array's
length
property and numerical properties are connected.
Several of the built-in array methods (e.g.,
join()
,
slice()
,
indexOf()
, etc.) take into account the value of an array's
length
property when they're called.
Other methods (e.g.,
push()
,
splice()
, etc.) also result in updates to an array's
length
property.
const fruits = [];
fruits.push("banana", "apple", "peach");
console.log(fruits.length); // 3
When setting a property on a JavaScript array when the property is a valid array index and that index is outside the current bounds of the array, the engine will update the array's length property accordingly:
fruits[5] = "mango";
console.log(fruits[5]); // 'mango'
console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
console.log(fruits.length); // 6
Increasing the length.
fruits.length = 10;
console.log(fruits); // ['banana', 'apple', 'peach', empty x 2, 'mango', empty x 4]
console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
console.log(fruits.length); // 10
console.log(fruits[8]); // undefined
Decreasing the length property does, however, delete elements.
fruits.length = 2;
console.log(Object.keys(fruits)); // ['0', '1']
console.log(fruits.length); // 2
This is explained further on the Array/length page.
Array methods and empty slots
Array methods and empty slots
Empty slots in
sparse arrays
behave inconsistently between array methods. Generally, the older methods will skip empty slots, while newer ones treat them as
undefined
.
Among methods that iterate through multiple elements, the following do an
in
check before accessing the index and do not conflate empty slots with
undefined
:
concat()
copyWithin()
every()
filter()
flat()
flatMap()
forEach()
indexOf()
lastIndexOf()
map()
reduce()
reduceRight()
reverse()
slice()
some()
sort()
splice()
For exactly how they treat empty slots, see the page for each method.
These methods treat empty slots as if they are
undefined
:
entries()
fill()
find()
findIndex()
findLast()
findLastIndex()
group()
Experimental
groupToMap()
Experimental
includes()
join()
keys()
toLocaleString()
values()
Copying methods and mutating methods
Copying methods and mutating methods
Some methods do not mutate the existing array that the method was called on, but instead return a new array. They do so by first constructing a new array and then populating it with elements. The copy always happens
shallowly
— the method never copies anything beyond the initially created array. Elements of the original array(s) are copied into the new array as follows:
Objects: the object reference is copied into the new array. Both the original and new array refer to the same object. That is, if a referenced object is modified, the changes are visible to both the new and original arrays.
Primitive types such as strings, numbers and booleans (not
String
,
Number
, and
Boolean
objects): their values are copied into the new array.
Other methods mutate the array that the method was called on, in which case their return value differs depending on the method: sometimes a reference to the same array, sometimes the length of the new array.
The following methods create new arrays by accessing
this.constructor[Symbol.species]
to determine the constructor to use:
concat()
filter()
flat()
flatMap()
map()
slice()
splice()
(to construct the array of removed elements that's returned)
The following methods always create new arrays with the
Array
base constructor:
toReversed()
toSorted()
toSpliced()
with()
group()
and
groupToMap()
do not use
@@species
to create new arrays for each group entry, but always use the plain
Array
constructor. Conceptually, they are not copying methods either.
The following table lists the methods that mutate the original array, and the corresponding non-mutating alternative:
Mutating method
Non-mutating alternative
An easy way to change a mutating method into a non-mutating alternative is to use the
spread syntax
or
slice()
to create a copy first:
arr.copyWithin(0, 1, 2); // mutates arr
const arr2 = arr.slice().copyWithin(0, 1, 2); // does not mutate arr
const arr3 = [...arr].copyWithin(0, 1, 2); // does not mutate arr
Iterative methods
Iterative methods
Many array methods take a callback function as an argument. The callback function is called sequentially and at most once for each element in the array, and the return value of the callback function is used to determine the return value of the method. They all share the same signature:
method(callbackFn, thisArg)
Where callbackFn takes three 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 that the method was called upon.
What callbackFn is expected to return depends on the array method that was called.
The thisArg argument (defaults to undefined) will be used as the this value when calling callbackFn. The this value ultimately observable by callbackFn is determined according to the usual rules: if callbackFn is non-strict, primitive this values are wrapped into objects, and undefined/null is substituted with globalThis. The thisArg argument is irrelevant for any callbackFn defined with an arrow function, as arrow functions don't have their own this binding.
All iterative methods are copying and generic, although they behave differently with empty slots.
The following methods are iterative:
every()
filter()
find()
findIndex()
findLast()
findLastIndex()
flatMap()
forEach()
group()
groupToMap()
map()
some()
In particular, every(), find(), findIndex(), findLast(), findLastIndex(), and some() do not always invoke callbackFn on every element — they stop iteration as soon as the return value is determined.
There are two other methods that take a callback function and run it at most once for each element in the array, but they have slightly different signatures from typical iterative methods (for example, they don't accept thisArg):
reduce()
reduceRight()
The sort() method also takes a callback function, but it is not an iterative method. It mutates the array in-place, doesn't accept thisArg, and may invoke the callback multiple times on an index.
Generic array methods
Generic array methods
Array methods are always generic — they don't access any internal data of the array object. They only access the array elements through the
length
property and the indexed elements. This means that they can be called on array-like objects as well.
const arrayLike = {
0: "a",
1: "b",
length: 2,
console.log(Array.
prototype.join.call(arrayLike, "+")); // 'a+b'
Normalization of the length property
The length property is converted to an integer and then clamped to the range between 0 and 253 - 1. NaN becomes 0, so even when length is not present or is undefined, it behaves as if it has value 0.
The language avoids setting length to an unsafe integer. All built-in methods will throw a TypeError if length will be set to a number greater than 253 - 1. However, because the length property of arrays throws an error if it's set to greater than 232, the safe integer threshold is usually not reached unless the method is called on a non-array object.
Array.prototype.flat.call({}); // []
Some array methods set the length property of the array object. They always set the value after normalization, so length always ends as an integer.
const a = { length: 0.7 };
Array.prototype.push.call(a);
console.log(a.length); // 0
Array-like objects
The term array-like object refers to any object that doesn't throw during the length conversion process described above. In practice, such object is expected to actually have a length property and to have indexed elements in the range 0 to length - 1. (If it doesn't have all indices, it will be functionally equivalent to a sparse array.)
Many DOM objects are array-like — for example, NodeList and HTMLCollection. The arguments object is also array-like. You can call array methods on them even if they don't have these methods themselves.
function f() {
console.log(Array.prototype.join.call(arguments, "+"));
f("a", "b"); // 'a+b'
Constructor
Constructor
-
Array()
Creates a new
Array
object.
Static properties
Static properties
-
Array[@@species]
Returns the
Array
constructor.
Static methods
Static methods
-
Array.from() -
Array.fromAsync()ExperimentalCreates a new
Arrayinstance from an async iterable, iterable, or array-like object. -
Array.isArray() -
Array.of()
Creates a new
Array
instance from an iterable or array-like object.
Returns
true
if the argument is an array, or
false
otherwise.
Creates a new
Array
instance with a variable number of arguments, regardless of number or type of the arguments.
Instance properties
Instance properties
These properties are defined on
Array.prototype
and shared by all
Array
instances.
Array.prototype.constructor
The constructor function that created the instance object. For
Array
instances, the initial value is the
Array
constructor.
Array.prototype[@@unscopables]
Contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored for
with
statement-binding purposes.
These properties are own properties of each
Array
instance.
length
Reflects the number of elements in an array.
Instance methods
Instance methods
-
Array.prototype.at() -
Array.prototype.concat() -
Array.prototype.copyWithin() -
Array.prototype.entries() -
Array.prototype.every() -
Array.prototype.fill() -
Array.prototype.filter() -
Array.prototype.find() -
Array.prototype.findIndex() -
Array.prototype.findLast() -
Array.prototype.findLastIndex() -
Array.prototype.flat() -
Array.prototype.flatMap() -
Array.prototype.forEach() -
Array.prototype.group()ExperimentalGroups the elements of an array into an object according to the strings returned by a test function.
-
Array.prototype.groupToMap()ExperimentalGroups the elements of an array into a
Mapaccording to values returned by a test function. -
Array.prototype.includes() -
Array.prototype.indexOf() -
Array.prototype.join() -
Array.prototype.keys() -
Array.prototype.lastIndexOf() -
Array.prototype.map() -
Array.prototype.pop() -
Array.prototype.push() -
Array.prototype.reduce() -
Array.prototype.reduceRight() -
Array.prototype.reverse() -
Array.prototype.shift() -
Array.prototype.slice() -
Array.prototype.some() -
Array.prototype.sort() -
Array.prototype.splice() -
Array.prototype.toLocaleString() -
Array.prototype.toReversed() -
Array.prototype.toSorted() -
Array.prototype.toSpliced() -
Array.prototype.toString() -
Array.prototype.unshift() -
Array.prototype.values() -
Array.prototype.with() -
Array.prototype[@@iterator]()
Returns the array item at the given index. Accepts negative integers, which count back from the last item.
Returns a new array that is the calling array joined with other array(s) and/or value(s).
Copies a sequence of array elements within an array.
Returns a new
array iterator
object that contains the key/value pairs for each index in an array.
Returns
true
if every element in the calling array satisfies the testing function.
Fills all the elements of an array from a start index to an end index with a static value.
Returns a new array containing all elements of the calling array for which the provided filtering function returns
true
.
Returns the value of the first element in the array that satisfies the provided testing function, or
undefined
if no appropriate element is found.
Returns the index of the first element in the array that satisfies the provided testing function, or
-1
if no appropriate element was found.
Returns the value of the last element in the array that satisfies the provided testing function, or
undefined
if no appropriate element is found.
Returns the index of the last element in the array that satisfies the provided testing function, or
-1
if no appropriate element was found.
Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.
Returns a new array formed by applying a given callback function to each element of the calling array, and then flattening the result by one level.
Calls a function for each element in the calling array.
Determines whether the calling array contains a value, returning
true
or
false
as appropriate.
Returns the first (least) index at which a given element can be found in the calling array.
Joins all elements of an array into a string.
Returns a new
array iterator
that contains the keys for each index in the calling array.
Returns the last (greatest) index at which a given element can be found in the calling array, or
-1
if none is found.
Returns a new array containing the results of invoking a function on every element in the calling array.
Removes the last element from an array and returns that element.
Adds one or more elements to the end of an array, and returns the new
length
of the array.
Executes a user-supplied "reducer" callback function on each element of the array (from left to right), to reduce it to a single value.
Executes a user-supplied "reducer" callback function on each element of the array (from right to left), to reduce it to a single value.
Reverses the order of the elements of an array
in place
. (First becomes the last, last becomes first.)
Removes the first element from an array and returns that element.
Extracts a section of the calling array and returns a new array.
Returns
true
if at least one element in the calling array satisfies the provided testing function.
Sorts the elements of an array in place and returns the array.
Adds and/or removes elements from an array.
Returns a localized string representing the calling array and its elements. Overrides the
Object.prototype.toLocaleString()
method.
Returns a new array with the elements in reversed order, without modifying the original array.
Returns a new array with the elements sorted in ascending order, without modifying the original array.
Returns a new array with some elements removed and/or replaced at a given index, without modifying the original array.
Returns a string representing the calling array and its elements. Overrides the
Object.prototype.toString()
method.
Adds one or more elements to the front of an array, and returns the new
length
of the array.
Returns a new
array iterator
object that contains the values for each index in the array.
Returns a new array with the element at the given index replaced with the given value, without modifying the original array.
An alias for the
values()
method by default.
Examples
Examples
This section provides some examples of common array operations in JavaScript.
Note:
If you're not yet familiar with array basics, consider first reading
JavaScript First Steps: Arrays
, which
explains what arrays are
, and includes other examples of common array operations.