There are multiple ways to add new elements at the beginning of an array in JavaScript.
1. Using unshift() Method
The unshift()
method add elements to the beginning of an array. It modifies the original array and returns the new length of the array.
Adding One Element
let arr = [10, 20, 30, 40, 50]; // Add 5 at the beginning arr.unshift(5); console.log(arr); // Output: [5, 10, 20, 30, 40, 50]
Adding Multiple Elements
let arr = [30, 40, 50]; arr.unshift(10, 20); console.log(arr); // Output: [10, 20, 30, 40, 50]
2. Using splice() Method
The splice()
method can insert elements at any position, including the beginning of the array.
let arr = [30, 40, 50]; arr.splice(0, 0, 10, 20); console.log(arr); // Output: [10, 20, 30, 40, 50]
3. Using Spread Operator (…)
The spread operator allows you to expand arrays, making it possible to add elements at the beginning without modifying the original array.
let arr = [30, 40, 50]; let newArr = [10, 20, ...arr]; console.log(newArr); // Output: [10, 20, 30, 40, 50]
4. Using concat() Method
The concat()
method combines arrays or values into a new array. It does not modify the original array.
let arr = [30, 40, 50]; let newArr = [10, 20].concat(arr); console.log(newArr); // Output: [10, 20, 30, 40, 50]
5. Using a for Loop
If you want to insert elements manually, you can use a for
loop to shift the existing elements and add new ones.
let arr = [20, 30, 40, 50]; let item = 10; // Shift elements manually for (let i = arr.length; i > 0; i--) { arr[i] = arr[i - 1]; } arr[0] = item; console.log(arr); // Output: [10, 20, 30, 40, 50]