Explain Codes LogoExplain Codes Logo

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

javascript
array-manipulation
performance
best-practices
Alex KataevbyAlex Kataev·Aug 18, 2024
TLDR

Crack open the unshift method to add items to the start of an array. Simple and effective.

let arr = [100, 200]; arr.unshift(0, 30); // Hello, new friends - [0, 30, 100, 200]

Strategies for array prepending

Using the spread operator

The ES6 spread syntax shines as a flexible tool for array manipulation, allowing new elements to be prepended effortlessly.

let oldBunch = [3, 4]; let newBunch = [1, 2, ...oldBunch]; // Party at the start - [1, 2, 3, 4]

Kudos to its non-destructive behavior as it leaves the source array untouched.

Leveraging concat to merge arrays

When in the mood for a non-aggressive approach, concat is the ideal candidate for a peaceful merge.

let arr = [100, 200]; let bigArr = [0, 30].concat(arr); // Join the club - [0, 30, 100, 200]

With concat at the helm, your source array dances around any unfortunate mutations, maintaining data integrity.

Considering performance

While unshift and spread operator do a fine job for most scenarios, for large datasets, concat might steal the performance show as unshift could slow due to element reindexing.

Deep dive into array operations

Exploring shift and unshift

The dynamic duo of unshift and shift offers robust tools for handling queue structures:

  • unshift: Adds elements to the start and gives back the updated length.
  • shift: Removes the first element and returns it, great for implementing queues in your applications.

Mastering array methods

Beyond unshift and concat, other potent array methods include push and pop:

  • push: Append elements to the tail end of an array.
  • pop: Remove the last element from an array, returning it smack in your hands.

These methods tinker with the array in-place, supporting efficient coding.

Handling standalone elements

For single elements, concat can do the trick once we wrap it in an array:

let arr = [100, 200]; let bigArr = [0].concat(arr); // Solo player joining the array party - [0, 100, 200]

Here's a demo of concat's single-element auto-wrapping feature, making syntax as smooth as butter.

Extras

  • For small arrays, the performance difference between methods is typically marginal. So stress more on readability and clarity.
  • The method choice largely depends on whether you intend to modify the original array or leave it unscathed. unshift modifies the original array, whereas concat and the spread operator don't.
  • For performance-critical code, it's wise to benchmark your code snippets since JavaScript engines vary across browsers and versions, and with ongoing optimization updates.