Logo

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

Adding new elements at the start of a JavaScript array is a common operation, especially when you want to build lists in chronological order (like messages, transactions, or activity logs). Below are some of the most straightforward and performance-friendly ways to prepend elements in JavaScript.

1. Using the unshift() Method

The most direct way is to use the built-in unshift() method:

const fruits = ["banana", "cherry"]; fruits.unshift("apple"); console.log(fruits); // Output: ["apple", "banana", "cherry"]
  • Explanation: unshift() inserts new items at the beginning of the array in place, returning the updated array length.
  • Time Complexity: This operation is generally O(n), because existing elements need to be re-indexed.

2. Using the Spread Operator

If you’re working in a framework or paradigm that favors immutability (e.g., React), you might prefer creating a new array:

const fruits = ["banana", "cherry"]; const newFruits = ["apple", ...fruits]; console.log(newFruits); // Output: ["apple", "banana", "cherry"]
  • Explanation: The spread operator (...) expands the existing array elements into a new array, ensuring the original remains untouched.

3. Using concat()

Similar to the spread operator, the concat() method also returns a new array without mutating the original:

const fruits = ["banana", "cherry"]; const newFruits = ["apple"].concat(fruits); console.log(newFruits); // Output: ["apple", "banana", "cherry"]
  • Use Case: Like spread, concat() is helpful for scenarios where you need to avoid modifying your initial array (useful in functional programming).

Performance Considerations

  1. Mutability vs. Immutability:

    • unshift() mutates the existing array, which can be fine for small or moderate data sets.
    • Using spread or concat() creates a new array, making them handy in frameworks that leverage immutable data structures.
  2. Scaling:

    • For large arrays with frequent insertions at the beginning, be mindful that re-indexing can be costly. If you need efficient prepends at scale, consider a data structure like a linked list.

Interview Insights

  1. Big-O Notation: Show you understand that prepending to an array (in JavaScript) is generally O(n), because of the element re-indexing.
  2. Use Cases: Discuss real-world scenarios like building a “recent activity” feed, maintaining user input history, or creating a queue-like structure.
  3. Clean Code: If you need immutability—like in Redux or React state—use spread or concat() to avoid side effects.

Master JavaScript with DesignGurus.io

If you’re looking to hone your JavaScript fundamentals or advance your coding skills for interviews, check out:

  • Grokking JavaScript Fundamentals – This course dives deep into core JavaScript concepts, best practices, and modern features, giving you the confidence to tackle front-end and full-stack challenges.

Beyond that, you can also explore more free tutorials on the DesignGurus YouTube Channel for hands-on coding demos and expert insights. And if you’re preparing for coding interviews, consider scheduling a Coding Mock Interview to get personalized feedback from ex-FAANG engineers.

Final Thoughts
Adding elements at the beginning of an array in JavaScript is easy with methods like unshift(), the spread operator, or concat(). Choose the right approach depending on your need for immutability and performance. With practice—and a solid grasp of the language fundamentals—you’ll find this task becomes second nature. Happy coding!

CONTRIBUTOR
TechGrind