Insert at the Beginning of an Array in JavaScript
Following are different ways to add new elements at the beginning of an array
1. Using the Array unshift() Method - Most Used:
Adding new elements at the beginning of the existing array can be done by using the Array unshift() method. This method is similar to the push() method but it adds an element at the beginning of the array.
let a = [2, 3, 4];
a.unshift(1);
console.log(a);
Output
[ 1, 2, 3, 4 ]
2. Using Array splice() Method
The array.splice method is used to modify the content of the array. we give the start, end the value as a parameter to the method so that it helps us to add the value in between the given start and end index.
let a = [2, 3, 4];
a.splice(0, 0, 1);
console.log(a);
Output
[ 1, 2, 3, 4 ]
3. Using the Spread Operator
The Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 value is expected.
let a = [2, 3, 4];
a = [1, ...a];
console.log(a);
Output
[ 1, 2, 3, 4 ]
4. Using Array concat() Method
The JavaScript Array concat() Method is used to merge two or more arrays together. you can add any element by just calling this function after the value.
const a = [2, 3, 4];
console.log([1].concat(a));
Output
[ 1, 2, 3, 4 ]