9, Jan 2023
How can I add new array elements at the beginning of an array in JavaScript?

There are several ways to add new elements to the beginning of an array in JavaScript. Here are a few options:
- Use the
unshift()
method:
let array = [1, 2, 3];
array.unshift(0);
console.log(array); // [0, 1, 2, 3]
- Use the
splice()
method:
let array = [1, 2, 3];
array.splice(0, 0, 0);
console.log(array); // [0, 1, 2, 3]
- Use the spread operator (
...
) and theconcat()
method:
let array = [1, 2, 3]; let newArray = [0].concat(array); console.log(newArray); // [0, 1, 2, 3] // or let newArray = [0, ...array]; console.log(newArray); // [0, 1, 2, 3]
- 0
- By dummy.greenrakshaagroseva.com



