Adding a new array element to the beginning of an array is something that we’ve to sometimes in our JavaScript apps.
In this article, we’ll look at how to add new array elements at the beginning of an array in JavaScript.
Array.prototype.concat
One way to add an element to the beginning of a JavaScript array is to use the concat
method.
We call concat
with a new array with the element we want to add.
Then we pass in the existing array as the argument.
For instance, we can write:
const array = [1, 2, 3]
const newFirstElement = 4
const newArray = [newFirstElement].concat(array)
console.log(newArray);
We have the array
array that we want to add a new first element to.
newFirstElement
is the first element we want to add.
To do this, we create a new array with newFirstElement
in it.
Then we call concat
with array
to concatenate array
to the new array we created.
A new array with both of them combined is returned, so newArray
is [4, 1, 2, 3]
.
Array.prototype.unshift
The unshift
method available with JavaScript arrays is specially made to add an element to the beginning of an array.
The addition of the element is done in place, so the array it’s called on is mutated.
For instance, we can write:
const array = [1, 2, 3]
array.unshift(4);
console.log(array);
Then array
is [4, 1, 2, 3]
.
Spread Operator
We can use the spread operator to add elements from one array to another by making a copy and putting the items in the new array.
For instance, if we have:
const array = [1, 2, 3]
const newArray = [4, ...array];
console.log(newArray);
Then all the items from array
are spread into the newArray
.
Therefore, newArray
is [4, 1, 2, 3]
.
Array.prototype.splice
Another way to add an element to the beginning of an array is to use the splice
method.
splice
changes an array it’s called in place.
For instance, we can write:
const array = [1, 2, 3]
array.splice(0, 0, 4);
console.log(array);
We call splice
with the index of array
we want to change in the first argument.
The 2nd argument is the number of elements we want to remove starting from the index we specified in the first argument.
And the last argument is the element we want to insert before the index we have in the first argument.
Therefore, array
should be [4, 1, 2, 3]
.
Conclusion
We can use array methods or the spread operator to add items to the beginning of an array with JavaScript.