In JavaScript, you can add an element to the start of an existing array in the following ways:
- Using the Spread Syntax (
...
); - Using
Array.prototype.concat()
; - Using
Array.prototype.unshift()
; - Using
Array.prototype.splice()
.
Using the Spread Syntax (...
)
You can create a new array to which you can add the new element as the first element, and unpack/expand the existing array(s) right after, for example, like so:
// ES6+ const existingArr = ['bar', 'baz']; const newArr = ['foo', ...existingArr]; console.log(newArr); // ['foo', 'bar', 'baz']
This does not mutate/modify the original array.
Using Array.prototype.concat()
You can use the Array.prototype.concat()
method to merge/join two (or more) arrays together — where the first array only has one element and the second one is the existing array. When both arrays are merged, a new array would be created with the element from the first array being the first element in the new array. For example:
const existingArr = ['bar', 'baz']; const newArr = ['foo'].concat(existingArr); console.log(newArr); // ['foo', 'bar', 'baz']
This does not mutate/modify the original array.
Using Array.prototype.unshift()
You can add an item to the front of an existing array using the Array.prototype.unshift()
method like so:
const existingArr = ['bar', 'baz']; existingArr.unshift('foo'); console.log(existingArr); // ['foo', 'bar', 'baz']
As you can see from the example above, using the Array.prototype.unshift()
method mutates/modifies the original array.
Using Array.prototype.splice()
You can add an item to the front of an existing array using the Array.prototype.splice()
method like so:
const existingArr = ['bar', 'baz']; existingArr.splice(0, 0, 'foo'); console.log(existingArr); // ['foo', 'bar', 'baz']
As you can see from the example above, using the Array.prototype.splice()
method mutates/modifies the original array.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.