Array

BaselineWidely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers sinceJuly 2015.

TheArrayobject, as with arrays in other programming languages, enablesstoring a collection of multiple items under a single variable name,and has members forperforming common array operations.

Description

In JavaScript, arrays aren'tprimitivesbut are insteadArrayobjects with the following core characteristics:

  • JavaScript arrays are resizableandcan contain a mix of differentdata types.(When those characteristics are undesirable, usetyped arraysinstead.)
  • JavaScript arrays are not associative arraysand so, array elements cannot be accessed using arbitrary strings as indexes, but must be accessed using nonnegative integers (or their respective string form) as indexes.
  • JavaScript arrays arezero-indexed:the first element of an array is at index0,the second is at index1,and so on — and the last element is at the value of the array'slengthproperty minus1.
  • JavaScriptarray-copy operationscreateshallow copies.(All standard built-in copy operations withanyJavaScript objects create shallow copies, rather thandeep copies).

Array indices

Arrayobjects cannot use arbitrary strings as element indexes (as in anassociative 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'sobject property collection.The array's object properties and list of array elements are separate, and the array'straversal and mutation operationscannot be applied to these named properties.

Array elements are object properties in the same way thattoStringis 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:

js
arr.0;// a syntax error

JavaScript syntax requires properties beginning with a digit to be accessed usingbracket notationinstead ofdot notation.It's also possible to quote the array indices (e.g.,years['2']instead ofyears[2]), although usually not necessary.

The2inyears[2]is coerced into a string by the JavaScript engine through an implicittoStringconversion. As a result,'2'and'02'would refer to two different slots on theyearsobject, and the following example could betrue:

js
console.log(years["2"]!==years["02"]);

Onlyyears['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

A JavaScript array'slengthproperty 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'slengthproperty when they're called.

Other methods (e.g.,push(),splice(),etc.) also result in updates to an array'slengthproperty.

js
constfruits=[];
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'slengthproperty accordingly:

js
fruits[5]="mango";
console.log(fruits[5]);// 'mango'
console.log(Object.keys(fruits));// ['0', '1', '2', '5']
console.log(fruits.length);// 6

Increasing thelengthextends the array by adding empty slots without creating any new elements — not evenundefined.

js
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 thelengthproperty does, however, delete elements.

js
fruits.length=2;
console.log(Object.keys(fruits));// ['0', '1']
console.log(fruits.length);// 2

This is explained further on thelengthpage.

Array methods and empty slots

Array methods have different behaviors when encountering empty slots insparse arrays.In general, older methods (e.g.forEach) treat empty slots differently from indices that containundefined.

Methods that have special treatment for empty slots include the following:concat(),copyWithin(),every(),filter(),flat(),flatMap(),forEach(),indexOf(),lastIndexOf(),map(),reduce(),reduceRight(),reverse(),slice(),some(),sort(),andsplice().Iteration methods such asforEachdon't visit empty slots at all. Other methods, such asconcat,copyWithin,etc., preserve empty slots when doing the copying, so in the end the array is still sparse.

js
constcolors=["red","yellow","blue"];
colors[5]="purple";
colors.forEach((item,index)=>{
console.log(`${index}:${item}`);
});
// Output:
// 0: red
// 1: yellow
// 2: blue
// 5: purple

colors.reverse();// ['purple', empty × 2, 'blue', 'yellow', 'red']

Newer methods (e.g.keys) do not treat empty slots specially and treat them as if they containundefined.Methods that conflate empty slots withundefinedelements include the following:entries(),fill(),find(),findIndex(),findLast(),findLastIndex(),includes(),join(),keys(),toLocaleString(),toReversed(),toSorted(),toSpliced(),values(),andwith().

js
constcolors=["red","yellow","blue"];
colors[5]="purple";
constiterator=colors.keys();
for(constkeyofiterator){
console.log(`${key}:${colors[key]}`);
}
// Output
// 0: red
// 1: yellow
// 2: blue
// 3: undefined
// 4: undefined
// 5: purple

constnewColors=colors.toReversed();// ['purple', undefined, undefined, 'blue', 'yellow', 'red']

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 happensshallowly— 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 (notString,Number,andBooleanobjects): 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 accessingthis.constructor[Symbol.species]to determine the constructor to use:concat(),filter(),flat(),flatMap(),map(),slice(),andsplice()(to construct the array of removed elements that's returned).

The following methods always create new arrays with theArraybase constructor:toReversed(),toSorted(),toSpliced(),andwith().

The following table lists the methods that mutate the original array, and the corresponding non-mutating alternative:

Mutating method Non-mutating alternative
copyWithin() No one-method alternative
fill() No one-method alternative
pop() slice(0, -1)
push(v1, v2) concat([v1, v2])
reverse() toReversed()
shift() slice(1)
sort() toSorted()
splice() toSpliced()
unshift(v1, v2) toSpliced(0, 0, v1, v2)

An easy way to change a mutating method into a non-mutating alternative is to use thespread syntaxorslice()to create a copy first:

js
arr.copyWithin(0,1,2);// mutates arr
constarr2=arr.slice().copyWithin(0,1,2);// does not mutate arr
constarr3=[...arr].copyWithin(0,1,2);// does not mutate arr

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:

js
method(callbackFn,thisArg)

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

WhatcallbackFnis expected to return depends on the array method that was called.

ThethisArgargument (defaults toundefined) will be used as thethisvalue when callingcallbackFn.Thethisvalue ultimately observable bycallbackFnis determined according tothe usual rules:ifcallbackFnisnon-strict,primitivethisvalues are wrapped into objects, andundefined/nullis substituted withglobalThis.ThethisArgargument is irrelevant for anycallbackFndefined with anarrow function,as arrow functions don't have their ownthisbinding.

Thearrayargument passed tocallbackFnis most useful if you want to read another index during iteration, because you may not always have an existing variable that refers to the current array. You should generally not mutate the array during iteration (seemutating initial array in iterative methods), but you can also use this argument to do so. Thearrayargument isnotthe array that is being built, in the case of methods likemap(),filter(),andflatMap()— there is no way to access the array being built from the callback function.

All iterative methods arecopyingandgeneric,although they behave differently withempty slots.

The following methods are iterative:every(),filter(),find(),findIndex(),findLast(),findLastIndex(),flatMap(),forEach(),map(),andsome().

In particular,every(),find(),findIndex(),findLast(),findLastIndex(),andsome()do not always invokecallbackFnon every element — they stop iteration as soon as the return value is determined.

Thereduce()andreduceRight()methods also 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 acceptthisArg).

Thesort()method also takes a callback function, but it is not an iterative method. It mutates the array in-place, doesn't acceptthisArg,and may invoke the callback multiple times on an index.

Iterative methods iterate the array like the following (with a lot of technical details omitted):

js
functionmethod(callbackFn,thisArg){
constlength=this.length;
for(leti=0;i<length;i++){
if(iinthis){
constresult=callbackFn.call(thisArg,this[i],i,this);
// Do something with result; maybe return early
}
}
}

Note the following:

  1. Not all methods do thei in thistest. Thefind,findIndex,findLast,andfindLastIndexmethods do not, but other methods do.
  2. Thelengthis memorized before the loop starts. This affects how insertions and deletions during iteration are handled (seemutating initial array in iterative methods).
  3. The method doesn't memorize the array contents, so if any index is modified during iteration, the new value might be observed.
  4. The code above iterates the array in ascending order of index. Some methods iterate in descending order of index (for (let i = length - 1; i >= 0; i--)):reduceRight(),findLast(),andfindLastIndex().
  5. reduceandreduceRighthave slightly different signatures and do not always start at the first/last element.

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 thelengthproperty and the indexed elements. This means that they can be called on array-like objects as well.

js
constarrayLike={
0:"a",
1:"b",
length:2,
};
console.log(Array.prototype.join.call(arrayLike,"+"));// 'a+b'

Normalization of the length property

Thelengthproperty isconverted to an integerand then clamped to the range between 0 and 253- 1.NaNbecomes0,so even whenlengthis not present or isundefined,it behaves as if it has value0.

The language avoids settinglengthto anunsafe integer.All built-in methods will throw aTypeErroriflengthwill be set to a number greater than 253- 1. However, because thelengthproperty of arrays throws an error if it's set to greater than 232- 1, the safe integer threshold is usually not reached unless the method is called on a non-array object.

js
Array.prototype.flat.call({});// []

Some array methods set thelengthproperty of the array object. They always set the value after normalization, solengthalways ends as an integer.

js
consta={length:0.7};
Array.prototype.push.call(a);
console.log(a.length);// 0

Array-like objects

The termarray-like objectrefers to any object that doesn't throw during thelengthconversion process described above. In practice, such object is expected to actually have alengthproperty and to have indexed elements in the range0tolength - 1.(If it doesn't have all indices, it will be functionally equivalent to asparse array.) Any integer index less than zero or greater thanlength - 1is ignored when an array method operates on an array-like object.

Many DOM objects are array-like — for example,NodeListandHTMLCollection.Theargumentsobject is also array-like. You can call array methods on them even if they don't have these methods themselves.

js
functionf(){
console.log(Array.prototype.join.call(arguments,"+"));
}

f("a","b");// 'a+b'

Constructor

Array()

Creates a newArrayobject.

Static properties

Array[@@species]

Returns theArrayconstructor.

Static methods

Array.from()

Creates a newArrayinstance from an iterable or array-like object.

Array.fromAsync()

Creates a newArrayinstance from an async iterable, iterable, or array-like object.

Array.isArray()

Returnstrueif the argument is an array, orfalseotherwise.

Array.of()

Creates a newArrayinstance with a variable number of arguments, regardless of number or type of the arguments.

Instance properties

These properties are defined onArray.prototypeand shared by allArrayinstances.

Array.prototype.constructor

The constructor function that created the instance object. ForArrayinstances, the initial value is theArrayconstructor.

Array.prototype[@@unscopables]

Contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored forwithstatement-binding purposes.

These properties are own properties of eachArrayinstance.

length

Reflects the number of elements in an array.

Instance methods

Array.prototype.at()

Returns the array item at the given index. Accepts negative integers, which count back from the last item.

Array.prototype.concat()

Returns a new array that is the calling array joined with other array(s) and/or value(s).

Array.prototype.copyWithin()

Copies a sequence of array elements within an array.

Array.prototype.entries()

Returns a newarray iteratorobject that contains the key/value pairs for each index in an array.

Array.prototype.every()

Returnstrueif every element in the calling array satisfies the testing function.

Array.prototype.fill()

Fills all the elements of an array from a start index to an end index with a static value.

Array.prototype.filter()

Returns a new array containing all elements of the calling array for which the provided filtering function returnstrue.

Array.prototype.find()

Returns the value of the first element in the array that satisfies the provided testing function, orundefinedif no appropriate element is found.

Array.prototype.findIndex()

Returns the index of the first element in the array that satisfies the provided testing function, or-1if no appropriate element was found.

Array.prototype.findLast()

Returns the value of the last element in the array that satisfies the provided testing function, orundefinedif no appropriate element is found.

Array.prototype.findLastIndex()

Returns the index of the last element in the array that satisfies the provided testing function, or-1if no appropriate element was found.

Array.prototype.flat()

Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.

Array.prototype.flatMap()

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.

Array.prototype.forEach()

Calls a function for each element in the calling array.

Array.prototype.includes()

Determines whether the calling array contains a value, returningtrueorfalseas appropriate.

Array.prototype.indexOf()

Returns the first (least) index at which a given element can be found in the calling array.

Array.prototype.join()

Joins all elements of an array into a string.

Array.prototype.keys()

Returns a newarray iteratorthat contains the keys for each index in the calling array.

Array.prototype.lastIndexOf()

Returns the last (greatest) index at which a given element can be found in the calling array, or-1if none is found.

Array.prototype.map()

Returns a new array containing the results of invoking a function on every element in the calling array.

Array.prototype.pop()

Removes the last element from an array and returns that element.

Array.prototype.push()

Adds one or more elements to the end of an array, and returns the newlengthof the array.

Array.prototype.reduce()

Executes a user-supplied "reducer" callback function on each element of the array (from left to right), to reduce it to a single value.

Array.prototype.reduceRight()

Executes a user-supplied "reducer" callback function on each element of the array (from right to left), to reduce it to a single value.

Array.prototype.reverse()

Reverses the order of the elements of an arrayin place.(First becomes the last, last becomes first.)

Array.prototype.shift()

Removes the first element from an array and returns that element.

Array.prototype.slice()

Extracts a section of the calling array and returns a new array.

Array.prototype.some()

Returnstrueif at least one element in the calling array satisfies the provided testing function.

Array.prototype.sort()

Sorts the elements of an array in place and returns the array.

Array.prototype.splice()

Adds and/or removes elements from an array.

Array.prototype.toLocaleString()

Returns a localized string representing the calling array and its elements. Overrides theObject.prototype.toLocaleString()method.

Array.prototype.toReversed()

Returns a new array with the elements in reversed order, without modifying the original array.

Array.prototype.toSorted()

Returns a new array with the elements sorted in ascending order, without modifying the original array.

Array.prototype.toSpliced()

Returns a new array with some elements removed and/or replaced at a given index, without modifying the original array.

Array.prototype.toString()

Returns a string representing the calling array and its elements. Overrides theObject.prototype.toString()method.

Array.prototype.unshift()

Adds one or more elements to the front of an array, and returns the newlengthof the array.

Array.prototype.values()

Returns a newarray iteratorobject that contains the values for each index in the array.

Array.prototype.with()

Returns a new array with the element at the given index replaced with the given value, without modifying the original array.

Array.prototype[@@iterator]()

An alias for thevalues()method by default.

Examples

This section provides some examples of common array operations in JavaScript.

Note:If you're not yet familiar with array basics, consider first readingJavaScript First Steps: Arrays,whichexplains what arrays are,and includes other examples of common array operations.

Create an array

This example shows three ways to create new array: first usingarray literal notation,then using theArray()constructor, and finally usingString.prototype.split()to build the array from a string.

js
// 'fruits' array created using array literal notation.
constfruits=["Apple","Banana"];
console.log(fruits.length);
// 2

// 'fruits2' array created using the Array() constructor.
constfruits2=newArray("Apple","Banana");
console.log(fruits2.length);
// 2

// 'fruits3' array created using String.prototype.split().
constfruits3="Apple, Banana".split(",");
console.log(fruits3.length);
// 2

Create a string from an array

This example uses thejoin()method to create a string from thefruitsarray.

js
constfruits=["Apple","Banana"];
constfruitsString=fruits.join(",");
console.log(fruitsString);
// "Apple, Banana"

Access an array item by its index

This example shows how to access items in thefruitsarray by specifying the index number of their position in the array.

js
constfruits=["Apple","Banana"];

// The index of an array's first element is always 0.
fruits[0];// Apple

// The index of an array's second element is always 1.
fruits[1];// Banana

// The index of an array's last element is always one
// less than the length of the array.
fruits[fruits.length-1];// Banana

// Using an index number larger than the array's length
// returns 'undefined'.
fruits[99];// undefined

Find the index of an item in an array

This example uses theindexOf()method to find the position (index) of the string"Banana"in thefruitsarray.

js
constfruits=["Apple","Banana"];
console.log(fruits.indexOf("Banana"));
// 1

Check if an array contains a certain item

This example shows two ways to check if thefruitsarray contains"Banana"and"Cherry":first with theincludes()method, and then with theindexOf()method to test for an index value that's not-1.

js
constfruits=["Apple","Banana"];

fruits.includes("Banana");// true
fruits.includes("Cherry");// false

// If indexOf() doesn't return -1, the array contains the given item.
fruits.indexOf("Banana")!==-1;// true
fruits.indexOf("Cherry")!==-1;// false

Append an item to an array

This example uses thepush()method to append a new string to thefruitsarray.

js
constfruits=["Apple","Banana"];
constnewLength=fruits.push("Orange");
console.log(fruits);
// [ "Apple", "Banana", "Orange" ]
console.log(newLength);
// 3

Remove the last item from an array

This example uses thepop()method to remove the last item from thefruitsarray.

js
constfruits=["Apple","Banana","Orange"];
constremovedItem=fruits.pop();
console.log(fruits);
// [ "Apple", "Banana" ]
console.log(removedItem);
// Orange

Note:pop()can only be used to remove the last item from an array. To remove multiple items from the end of an array, see the next example.

Remove multiple items from the end of an array

This example uses thesplice()method to remove the last 3 items from thefruitsarray.

js
constfruits=["Apple","Banana","Strawberry","Mango","Cherry"];
conststart=-3;
constremovedItems=fruits.splice(start);
console.log(fruits);
// [ "Apple", "Banana" ]
console.log(removedItems);
// [ "Strawberry", "Mango", "Cherry" ]

Truncate an array down to just its first N items

This example uses thesplice()method to truncate thefruitsarray down to just its first 2 items.

js
constfruits=["Apple","Banana","Strawberry","Mango","Cherry"];
conststart=2;
constremovedItems=fruits.splice(start);
console.log(fruits);
// [ "Apple", "Banana" ]
console.log(removedItems);
// [ "Strawberry", "Mango", "Cherry" ]

Remove the first item from an array

This example uses theshift()method to remove the first item from thefruitsarray.

js
constfruits=["Apple","Banana"];
constremovedItem=fruits.shift();
console.log(fruits);
// [ "Banana" ]
console.log(removedItem);
// Apple

Note:shift()can only be used to remove the first item from an array. To remove multiple items from the beginning of an array, see the next example.

Remove multiple items from the beginning of an array

This example uses thesplice()method to remove the first 3 items from thefruitsarray.

js
constfruits=["Apple","Strawberry","Cherry","Banana","Mango"];
conststart=0;
constdeleteCount=3;
constremovedItems=fruits.splice(start,deleteCount);
console.log(fruits);
// [ "Banana", "Mango" ]
console.log(removedItems);
// [ "Apple", "Strawberry", "Cherry" ]

Add a new first item to an array

This example uses theunshift()method to add, at index0,a new item to thefruitsarray — making it the new first item in the array.

js
constfruits=["Banana","Mango"];
constnewLength=fruits.unshift("Strawberry");
console.log(fruits);
// [ "Strawberry", "Banana", "Mango" ]
console.log(newLength);
// 3

Remove a single item by index

This example uses thesplice()method to remove the string"Banana"from thefruitsarray — by specifying the index position of"Banana".

js
constfruits=["Strawberry","Banana","Mango"];
conststart=fruits.indexOf("Banana");
constdeleteCount=1;
constremovedItems=fruits.splice(start,deleteCount);
console.log(fruits);
// [ "Strawberry", "Mango" ]
console.log(removedItems);
// [ "Banana" ]

Remove multiple items by index

This example uses thesplice()method to remove the strings"Banana"and"Strawberry"from thefruitsarray — by specifying the index position of"Banana",along with a count of the number of total items to remove.

js
constfruits=["Apple","Banana","Strawberry","Mango"];
conststart=1;
constdeleteCount=2;
constremovedItems=fruits.splice(start,deleteCount);
console.log(fruits);
// [ "Apple", "Mango" ]
console.log(removedItems);
// [ "Banana", "Strawberry" ]

Replace multiple items in an array

This example uses thesplice()method to replace the last 2 items in thefruitsarray with new items.

js
constfruits=["Apple","Banana","Strawberry"];
conststart=-2;
constdeleteCount=2;
constremovedItems=fruits.splice(start,deleteCount,"Mango","Cherry");
console.log(fruits);
// [ "Apple", "Mango", "Cherry" ]
console.log(removedItems);
// [ "Banana", "Strawberry" ]

Iterate over an array

This example uses afor...ofloop to iterate over thefruitsarray, logging each item to the console.

js
constfruits=["Apple","Mango","Cherry"];
for(constfruitoffruits){
console.log(fruit);
}
// Apple
// Mango
// Cherry

Butfor...ofis just one of many ways to iterate over any array; for more ways, seeLoops and iteration,and see the documentation for theevery(),filter(),flatMap(),map(),reduce(),andreduceRight()methods — and see the next example, which uses theforEach()method.

Call a function on each element in an array

This example uses theforEach()method to call a function on each element in thefruitsarray; the function causes each item to be logged to the console, along with the item's index number.

js
constfruits=["Apple","Mango","Cherry"];
fruits.forEach((item,index,array)=>{
console.log(item,index);
});
// Apple 0
// Mango 1
// Cherry 2

Merge multiple arrays together

This example uses theconcat()method to merge thefruitsarray with amoreFruitsarray, to produce a newcombinedFruitsarray. Notice thatfruitsandmoreFruitsremain unchanged.

js
constfruits=["Apple","Banana","Strawberry"];
constmoreFruits=["Mango","Cherry"];
constcombinedFruits=fruits.concat(moreFruits);
console.log(combinedFruits);
// [ "Apple", "Banana", "Strawberry", "Mango", "Cherry" ]

// The 'fruits' array remains unchanged.
console.log(fruits);
// [ "Apple", "Banana", "Strawberry" ]

// The 'moreFruits' array also remains unchanged.
console.log(moreFruits);
// [ "Mango", "Cherry" ]

Copy an array

This example shows three ways to create a new array from the existingfruitsarray: first by usingspread syntax,then by using thefrom()method, and then by using theslice()method.

js
constfruits=["Strawberry","Mango"];

// Create a copy using spread syntax.
constfruitsCopy=[...fruits];
// [ "Strawberry", "Mango" ]

// Create a copy using the from() method.
constfruitsCopy2=Array.from(fruits);
// [ "Strawberry", "Mango" ]

// Create a copy using the slice() method.
constfruitsCopy3=fruits.slice();
// [ "Strawberry", "Mango" ]

All built-in array-copy operations (spread syntax,Array.from(),Array.prototype.slice(),andArray.prototype.concat()) createshallow copies.If you instead want adeep copyof an array, you can useJSON.stringify()to convert the array to a JSON string, and thenJSON.parse()to convert the string back into a new array that's completely independent from the original array.

js
constfruitsDeepCopy=JSON.parse(JSON.stringify(fruits));

You can also create deep copies using thestructuredClone()method, which has the advantage of allowingtransferable objectsin the source to betransferredto the new copy, rather than just cloned.

Finally, it's important to understand that assigning an existing array to a new variable doesn't create a copy of either the array or its elements. Instead the new variable is just a reference, or alias, to the original array; that is, the original array's name and the new variable name are just two names for the exact same object (and so will always evaluate asstrictly equivalent). Therefore, if you make any changes at all either to the value of the original array or to the value of the new variable, the other will change, too:

js
constfruits=["Strawberry","Mango"];
constfruitsAlias=fruits;
// 'fruits' and 'fruitsAlias' are the same object, strictly equivalent.
fruits===fruitsAlias;// true
// Any changes to the 'fruits' array change 'fruitsAlias' too.
fruits.unshift("Apple","Banana");
console.log(fruits);
// ['Apple', 'Banana', 'Strawberry', 'Mango']
console.log(fruitsAlias);
// ['Apple', 'Banana', 'Strawberry', 'Mango']

Creating a two-dimensional array

The following creates a chessboard as a two-dimensional array of strings. The first move is made by copying the'p'inboard[6][4]toboard[4][4].The old position at[6][4]is made blank.

js
constboard=[
["R","N","B","Q","K","B","N","R"],
["P","P","P","P","P","P","P","P"],
["","","","","","","",""],
["","","","","","","",""],
["","","","","","","",""],
["","","","","","","",""],
["p","p","p","p","p","p","p","p"],
["r","n","b","q","k","b","n","r"],
];

console.log(`${board.join("\n")}\n\n`);

// Move King's Pawn forward 2
board[4][4]=board[6][4];
board[6][4]="";
console.log(board.join("\n"));

Here is the output:

R,N,B,Q,K,B,N,R
P,P,P,P,P,P,P,P
......,
......,
......,
......,
p,p,p,p,p,p,p,p
r,n,b,q,k,b,n,r

R,N,B,Q,K,B,N,R
P,P,P,P,P,P,P,P
......,
......,
...,p,,,
......,
p,p,p,p,,p,p,p
r,n,b,q,k,b,n,r

Using an array to tabulate a set of values

js
constvalues=[];
for(letx=0;x<10;x++){
values.push([2**x,2*x**2]);
}
console.table(values);

Results in

// The first column is the index
0 1 0
1 2 2
2 4 8
3 8 18
4 16 32
5 32 50
6 64 72
7 128 98
8 256 128
9 512 162

Creating an array using the result of a match

The result of a match between aRegExpand a string can create a JavaScript array that has properties and elements which provide information about the match. Such an array is returned byRegExp.prototype.exec()andString.prototype.match().

For example:

js
// Match one d followed by one or more b's followed by one d
// Remember matched b's and the following d
// Ignore case

constmyRe=/d(b+)(d)/i;
constexecResult=myRe.exec("cdbBdbsbz");

console.log(execResult.input);// 'cdbBdbsbz'
console.log(execResult.index);// 1
console.log(execResult);// [ "dbBd", "bB", "d" ]

For more information about the result of a match, see theRegExp.prototype.exec()andString.prototype.match()pages.

Mutating initial array in iterative methods

Iterative methodsdo not mutate the array on which it is called, but the function provided ascallbackFncan. The key principle to remember is that only indexes between 0 andarrayLength - 1are visited, wherearrayLengthis the length of the array at the time the array method was first called, but the element passed to the callback is the value at the time the index is visited. Therefore:

  • callbackFnwill not visit any elements added beyond the array's initial length when the call to the iterative method began.
  • Changes to already-visited indexes do not causecallbackFnto be invoked on them again.
  • If an existing, yet-unvisited element of the array is changed bycallbackFn,its value passed to thecallbackFnwill be the value at the time that element gets visited. Removed elements are not visited.

Warning:Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).

The following examples use theforEachmethod as an example, but other methods that visit indexes in ascending order work in the same way. We will first define a helper function:

js
functiontestSideEffect(effect){
constarr=["e1","e2","e3","e4"];
arr.forEach((elem,index,arr)=>{
console.log(`array: [${arr.join(",")}], index:${index},elem:${elem}`);
effect(arr,index);
});
console.log(`Final array: [${arr.join(",")}]`);
}

Modification to indexes not visited yet will be visible once the index is reached:

js
testSideEffect((arr,index)=>{
if(index+1<arr.length)arr[index+1]+="*";
});
// array: [e1, e2, e3, e4], index: 0, elem: e1
// array: [e1, e2*, e3, e4], index: 1, elem: e2*
// array: [e1, e2*, e3*, e4], index: 2, elem: e3*
// array: [e1, e2*, e3*, e4*], index: 3, elem: e4*
// Final array: [e1, e2*, e3*, e4*]

Modification to already visited indexes does not change iteration behavior, although the array will be different afterwards:

js
testSideEffect((arr,index)=>{
if(index>0)arr[index-1]+="*";
});
// array: [e1, e2, e3, e4], index: 0, elem: e1
// array: [e1, e2, e3, e4], index: 1, elem: e2
// array: [e1*, e2, e3, e4], index: 2, elem: e3
// array: [e1*, e2*, e3, e4], index: 3, elem: e4
// Final array: [e1*, e2*, e3*, e4]

Insertingnelements at unvisited indexes that are less than the initial array length will make them be visited. The lastnelements in the original array that now have index greater than the initial array length will not be visited:

js
testSideEffect((arr,index)=>{
if(index===1)arr.splice(2,0,"new");
});
// array: [e1, e2, e3, e4], index: 0, elem: e1
// array: [e1, e2, e3, e4], index: 1, elem: e2
// array: [e1, e2, new, e3, e4], index: 2, elem: new
// array: [e1, e2, new, e3, e4], index: 3, elem: e3
// Final array: [e1, e2, new, e3, e4]
// e4 is not visited because it now has index 4

Insertingnelements with index greater than the initial array length will not make them be visited:

js
testSideEffect((arr)=>arr.push("new"));
// array: [e1, e2, e3, e4], index: 0, elem: e1
// array: [e1, e2, e3, e4, new], index: 1, elem: e2
// array: [e1, e2, e3, e4, new, new], index: 2, elem: e3
// array: [e1, e2, e3, e4, new, new, new], index: 3, elem: e4
// Final array: [e1, e2, e3, e4, new, new, new, new]

Insertingnelements at already visited indexes will not make them be visited, but it shifts remaining elements back byn,so the current index and then - 1elements before it are visited again:

js
testSideEffect((arr,index)=>arr.splice(index,0,"new"));
// array: [e1, e2, e3, e4], index: 0, elem: e1
// array: [new, e1, e2, e3, e4], index: 1, elem: e1
// array: [new, new, e1, e2, e3, e4], index: 2, elem: e1
// array: [new, new, new, e1, e2, e3, e4], index: 3, elem: e1
// Final array: [new, new, new, new, e1, e2, e3, e4]
// e1 keeps getting visited because it keeps getting shifted back

Deletingnelements at unvisited indexes will make them not be visited anymore. Because the array has shrunk, the lastniterations will visit out-of-bounds indexes. If the method ignores non-existent indexes (seearray methods and empty slots), the lastniterations will be skipped; otherwise, they will receiveundefined:

js
testSideEffect((arr,index)=>{
if(index===1)arr.splice(2,1);
});
// array: [e1, e2, e3, e4], index: 0, elem: e1
// array: [e1, e2, e3, e4], index: 1, elem: e2
// array: [e1, e2, e4], index: 2, elem: e4
// Final array: [e1, e2, e4]
// Does not visit index 3 because it's out-of-bounds

// Compare this with find(), which treats nonexistent indexes as undefined:
constarr2=["e1","e2","e3","e4"];
arr2.find((elem,index,arr)=>{
console.log(`array: [${arr.join(",")}], index:${index},elem:${elem}`);
if(index===1)arr.splice(2,1);
returnfalse;
});
// array: [e1, e2, e3, e4], index: 0, elem: e1
// array: [e1, e2, e3, e4], index: 1, elem: e2
// array: [e1, e2, e4], index: 2, elem: e4
// array: [e1, e2, e4], index: 3, elem: undefined

Deletingnelements at already visited indexes does not change the fact that they were visited before they get deleted. Because the array has shrunk, the nextnelements after the current index are skipped. If the method ignores non-existent indexes, the lastniterations will be skipped; otherwise, they will receiveundefined:

js
testSideEffect((arr,index)=>arr.splice(index,1));
// array: [e1, e2, e3, e4], index: 0, elem: e1
// Does not visit e2 because e2 now has index 0, which has already been visited
// array: [e2, e3, e4], index: 1, elem: e3
// Does not visit e4 because e4 now has index 1, which has already been visited
// Final array: [e2, e4]
// Index 2 is out-of-bounds, so it's not visited

// Compare this with find(), which treats nonexistent indexes as undefined:
constarr2=["e1","e2","e3","e4"];
arr2.find((elem,index,arr)=>{
console.log(`array: [${arr.join(",")}], index:${index},elem:${elem}`);
arr.splice(index,1);
returnfalse;
});
// array: [e1, e2, e3, e4], index: 0, elem: e1
// array: [e2, e3, e4], index: 1, elem: e3
// array: [e2, e4], index: 2, elem: undefined
// array: [e2, e4], index: 3, elem: undefined

For methods that iterate in descending order of index, insertion causes elements to be skipped, and deletion causes elements to be visited multiple times. Adjust the code above yourself to see the effects.

Specifications

Specification
ECMAScript Language Specification
#sec-array-objects

Browser compatibility

BCD tables only load in the browser

See also