let num = [1, 2, 3, 4, 5];
console.log(num, typeof num);
// Expected output: [1, 2, 3, 4, 5] object
toString()
The toString()
method of Array
instances returns a string representing the specified array and its elements.
const array1 = [1, 2, 'a', '1a'];
console.log(array1.toString());
// Expected output: "1,2,a,1a"
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]
.
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.
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.
const arr = [];
arr.push(1, [3, arr, 4], 2);
console.log(arr.toString()); // 1,3,,4,2
join()
The join()
method of Array
instances creates and returns a new string by concatenating all of the elements in this array, separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join());
// Expected output: "Fire,Air,Water"
console.log(elements.join(''));
// Expected output: "FireAirWater"
console.log(elements.join('-'));
// Expected output: "Fire-Air-Water"
delete()
let num = [1, 2, 3, 4, 5];
console.log(num.length);
// Expected output: 5
delete num[0];
console.log(num);
// Expected output: [ <1 empty item>, 2, 3, 4, 5 ]
console.log(num.length);
// Expected output: 5
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.
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
console.log(array3);
// Expected output: Array ["a", "b", "c", "d", "e", "f"]
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]
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]
const letters = ["a", "b", "c"];
const alphaNumeric = letters.concat(1, [2, 3]);
console.log(alphaNumeric);
// results in ['a', 'b', 'c', 1, 2, 3]
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]]
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
).
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 ]
If any of the source arrays is sparse, the resulting array will also be sparse:
console.log([1, , 3].concat([4, 5])); // [1, empty, 3, 4, 5]
console.log([1, 2].concat([3, , 5])); // [1, 2, 3, empty, 5]
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.
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]
sort()
The sort()
method of Array
instances sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values. The time and space complexity of the sort cannot be guaranteed as it depends on the implementation. To sort the elements in an array without mutating the original array, use toSorted()
.
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// Expected output: Array ["Dec", "Feb", "Jan", "March"]
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// Expected output: Array [1, 100000, 21, 30, 4]
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. 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.
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]
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.
console.log(["a", "c", , "b"].toSorted()); // ['a', 'b', 'c', undefined]
console.log([, undefined, "a", "b"].toSorted()); // ["a", "b", undefined, undefined]
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.
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]
reverse()
The reverse()
method of Array
instances reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated. To reverse the elements in an array without mutating the original array, use toReversed()
.
const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// Expected output: "array1:" Array ["one", "two", "three"]
const reversed = array1.reverse();
console.log('reversed:', reversed);
// Expected output: "reversed:" Array ["three", "two", "one"]
// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1);
// Expected output: "array1:" Array ["three", "two", "one"]
The reverse()
method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array.
The reverse()
method preserves empty slots. If the source array is sparse, the empty slots' corresponding new indices are deleted and also become empty slots.
The reverse()
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.
Reversing the elements in an array
The following example creates an array items
, containing three elements, then reverses the array. The call to reverse()
returns a reference to the reversed array items
.
const items = [1, 2, 3];
console.log(items); // [1, 2, 3]
items.reverse();
console.log(items); // [3, 2, 1]
The reverse() method returns the reference to the same array
The reverse()
method returns reference to the original array, so mutating the returned array will mutate the original array as well.
const numbers = [3, 2, 4, 1, 5];
const reversed = numbers.reverse();
// numbers and reversed are both in reversed order [5, 1, 4, 2, 3]
reversed[0] = 5;
console.log(numbers[0]); // 5
In case you want reverse()
to not mutate the original array, but return a shallow-copied array like other array methods (e.g. map()
) do, use the toReversed()
method. Alternatively, you can do a shallow copy before calling reverse()
, using the spread syntax or Array.from()
.
const numbers = [3, 2, 4, 1, 5];
// [...numbers] creates a shallow copy, so reverse() does not mutate the original
const reverted = [...numbers].reverse();
reverted[0] = 5;
console.log(numbers[0]); // 3
Using reverse() on sparse arrays
Sparse arrays remain sparse after calling reverse()
. Empty slots are copied over to their respective new indices as empty slots.
console.log([1, , 3].reverse()); // [3, empty, 1]
console.log([1, , 3, 4].reverse()); // [4, 3, empty, 1]
Calling reverse() on non-array objects
The reverse()
method reads the length
property of this
. It then visits each property having an integer key between 0
and length / 2
, and swaps the two corresponding indices on both ends, deleting any destination property for which the source property did not exist.
const arrayLike = {
length: 3,
unrelated: "foo",
2: 4,
3: 33, // ignored by reverse() since length is 3
};
console.log(Array.prototype.reverse.call(arrayLike));
// { 0: 4, 3: 33, length: 3, unrelated: 'foo' }
// The index 2 is deleted because there was no index 0 present originally
// The index 3 is unchanged since the length is 3
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.
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.
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]
The return value of toReversed()
is never sparse. Empty slots become undefined
in the returned array.
console.log([1, , 3].toReversed()); // [3, undefined, 1]
console.log([1, , 3, 4].toReversed()); // [4, 3, undefined, 1]
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.
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
splice()
The splice()
method of Array
instances changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To create a new array with a segment removed and/or replaced without mutating the original array, use toSpliced()
. To access part of an array without modifying it, see slice()
.
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// Inserts at index 1
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "June"]
months.splice(4, 1, 'May');
// Replaces 1 element at index 4
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "May"]
The splice()
method is a mutating method. It may change the content of this
. If the specified number of elements to insert differs from the number of elements being removed, the array's length
will be changed as well. At the same time, it uses @@species
to create a new array instance to be returned.
If the deleted portion is sparse, the array returned by splice()
is sparse as well, with those corresponding indices being empty slots.
The splice()
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.
const myFish = ["angel", "clown", "mandarin", "sturgeon"];
const removed = myFish.splice(2, 0, "drum");
// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]
// removed is [], no elements removed
const myFish = ["angel", "clown", "mandarin", "sturgeon"];
const removed = myFish.splice(2, 0, "drum", "guitar");
// myFish is ["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"]
// removed is [], no elements removed
const myFish = ["angel", "clown", "drum", "mandarin", "sturgeon"];
const removed = myFish.splice(3, 1);
// myFish is ["angel", "clown", "drum", "sturgeon"]
// removed is ["mandarin"]
const myFish = ["angel", "clown", "drum", "sturgeon"];
const removed = myFish.splice(2, 1, "trumpet");
// myFish is ["angel", "clown", "trumpet", "sturgeon"]
// removed is ["drum"]
const myFish = ["angel", "clown", "trumpet", "sturgeon"];
const removed = myFish.splice(0, 2, "parrot", "anemone", "blue");
// myFish is ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
// removed is ["angel", "clown"]
const myFish = ["parrot", "anemone", "blue", "trumpet", "sturgeon"];
const removed = myFish.splice(2, 2);
// myFish is ["parrot", "anemone", "sturgeon"]
// removed is ["blue", "trumpet"]
const myFish = ["angel", "clown", "mandarin", "sturgeon"];
const removed = myFish.splice(-2, 1);
// myFish is ["angel", "clown", "sturgeon"]
// removed is ["mandarin"]
const myFish = ["angel", "clown", "mandarin", "sturgeon"];
const removed = myFish.splice(2);
// myFish is ["angel", "clown"]
// removed is ["mandarin", "sturgeon"]
The splice()
method preserves the array's sparseness.
const arr = [1, , 3, 4, , 6];
console.log(arr.splice(1, 2)); // [empty, 3]
console.log(arr); // [1, 4, empty, 6]
The splice()
method reads the length
property of this
. It then updates the integer-keyed properties and the length
property as needed.
const arrayLike = {
length: 3,
unrelated: "foo",
0: 5,
2: 4,
};
console.log(Array.prototype.splice.call(arrayLike, 0, 1, 2, 3));
// [ 5 ]
console.log(arrayLike);
// { '0': 2, '1': 3, '3': 4, length: 4, unrelated: 'foo' }
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.
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.
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()
.
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"]
The toSpliced()
method always creates a dense array.
const arr = [1, , 3, 4, , 6];
console.log(arr.toSpliced(1, 2)); // [1, 4, undefined, 6]
The toSpliced()
method reads the length
property of this
. It then reads the integer-keyed properties needed and writes them into the new array.
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]
slice()
The slice()
method of Array
instances returns a shallow copy of a portion of an array into a new array object selected from start
to end
(end
not included) where start
and end
represent the index of items in that array. The original array will not be modified.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// Expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// Expected output: Array ["camel", "duck"]
console.log(animals.slice(1, 5));
// Expected output: Array ["bison", "camel", "duck", "elephant"]
console.log(animals.slice(-2));
// Expected output: Array ["duck", "elephant"]
console.log(animals.slice(2, -1));
// Expected output: Array ["camel", "duck"]
console.log(animals.slice());
// Expected output: Array ["ant", "bison", "camel", "duck", "elephant"]
The slice()
method is a copying method. It does not alter this
but instead returns a shallow copy that contains some of the same elements as the ones from the original array.
The slice()
method preserves empty slots. If the sliced portion is sparse, the returned array is sparse as well.
The slice()
method is generic. It only expects the this
value to have a length
property and integer-keyed properties.
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1, 3);
// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus contains ['Orange','Lemon']
In the following example, slice
creates a new array, newCar
, from myCar
. Both include a reference to the object myHonda
. When the color of myHonda
is changed to purple, both arrays reflect the change.
// Using slice, create newCar from myCar.
const myHonda = {
color: "red",
wheels: 4,
engine: { cylinders: 4, size: 2.2 },
};
const myCar = [myHonda, 2, "cherry condition", "purchased 1997"];
const newCar = myCar.slice(0, 2);
console.log("myCar =", myCar);
console.log("newCar =", newCar);
console.log("myCar[0].color =", myCar[0].color);
console.log("newCar[0].color =", newCar[0].color);
// Change the color of myHonda.
myHonda.color = "purple";
console.log("The new color of my Honda is", myHonda.color);
console.log("myCar[0].color =", myCar[0].color);
console.log("newCar[0].color =", newCar[0].color);
The slice()
method reads the length
property of this
. It then reads the integer-keyed properties from start
to end
and defines them on a newly created array.
const arrayLike = {
length: 3,
0: 2,
1: 3,
2: 4,
3: 33, // ignored by slice() since length is 3
};
console.log(Array.prototype.slice.call(arrayLike, 1, 3));
// [ 3, 4 ]
The slice()
method is often used with bind()
and call()
to create a utility method that converts an array-like object into an array.
// slice() is called with `this` passed as the first argument
const slice = Function.prototype.call.bind(Array.prototype.slice);
function list() {
return slice(arguments);
}
const list1 = list(1, 2, 3); // [1, 2, 3]
The array returned from slice()
may be sparse if the source is sparse.
console.log([1, 2, , 4, 5].slice(1, 4)); // [2, empty, 4]