How can I add new array elements at the beginning of an array in JavaScript?

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:

  1. Use the unshift() method:
let array = [1, 2, 3];

array.unshift(0);

console.log(array);  // [0, 1, 2, 3]
  1. Use the splice() method:
let array = [1, 2, 3];

array.splice(0, 0, 0);

console.log(array);  // [0, 1, 2, 3]
  1. Use the spread operator (...) and the concat() 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]

Leave a Reply