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

To add new elements at the beginning of an array in JavaScript, you have a few options:

1. unshift() (Mutates the Original Array)

The most common method to prepend elements while modifying the original array:

const arr = [2, 3, 4];
arr.unshift(1); // Adds 1 to the start
console.log(arr); // [1, 2, 3, 4]

Add Multiple Elements:

arr.unshift(-1, 0); // Adds -1 and 0 to the start
console.log(arr); // [-1, 0, 1, 2, 3, 4]

Return Value:

  • unshift() returns the new array length:
  const length = arr.unshift(99); 
  console.log(length); // e.g., 6

2. Spread Operator (Non-Mutating)

Create a new array without modifying the original:

const arr = [2, 3, 4];
const newArr = [1, ...arr]; // Prepend 1
console.log(newArr); // [1, 2, 3, 4]

Add Multiple Elements:

const newArr = [-1, 0, ...arr]; // Prepends -1 and 0
console.log(newArr); // [-1, 0, 2, 3, 4]

3. concat() (Non-Mutating)

Combine arrays to prepend elements:

const arr = [2, 3, 4];
const newArr = [1].concat(arr); // Prepend 1
console.log(newArr); // [1, 2, 3, 4]

Key Notes

  • Mutating vs. Non-Mutating:
  • unshift() modifies the original array.
  • Spread operator and concat() create new arrays.
  • Performance:
  • unshift() is efficient for small arrays but has an O(n) time complexity (slower for large arrays).
  • Spread/concat() are generally fast but create memory overhead for copies.

Edge Cases

Empty Array:

const arr = [];
arr.unshift(1); // [1]

Prepending an Array as a Single Element:

const arr = [2, 3];
arr.unshift([1]); 
console.log(arr); // [[1], 2, 3] (array nested at index 0)

Summary

  • Use unshift() to mutate the original array.
  • Use the spread operator or concat() for immutability.
  • Choose based on whether you need to modify the original array or create a new one.

Leave a Reply

Your email address will not be published. Required fields are marked *