How do you prepend new elements to the beginning of a JavaScript array? | A1Lab@FahadM to JavaScriptEnglish • 4 days ago

How do you prepend new elements to the beginning of a JavaScript array?

message-square
0

To prepend new elements to the beginning of a JavaScript array without mutating the original array, use spread syntax ([...prependedItems, ...originalArray]) or Array.prototype.concat() (prependedItems.concat(originalArray)). While Array.prototype.unshift() also adds items to the start of an array, it mutates the array in place and shifts every existing index—making immutable spread ([...items, ...arr]) safer for state, props, and shared arrays.


1. Non-Mutating Prepend with Spread Syntax ([...items, ...arr])

Validate that the base array and prepended items are arrays (or normalize single/iterable inputs safely) and return a brand-new array starting with the new elements followed by the original items:

// Prepend elements to the start of an array without mutating the original array
function prependToArray(targetArray, ...elementsToPrepend) {
  if (!Array.isArray(targetArray)) {
    throw new TypeError("Expected targetArray to be an Array.");
  }

  const itemsToAdd =
    elementsToPrepend.length === 1 && Array.isArray(elementsToPrepend[0])
      ? elementsToPrepend[0]
      : elementsToPrepend;

  return [...itemsToAdd, ...targetArray];
}

// Example usage:
const queue = Object.freeze(["task-2", "task-3"]);
const nextQueue = prependToArray(queue, ["task-0", "task-1"]);
console.log("Prepended:", nextQueue); // ["task-0", "task-1", "task-2", "task-3"]
console.log("Original untouched:", queue); // ["task-2", "task-3"]
  • Immutable by default: Leaves targetArray untouched and returns a new array reference.
  • Preserves order: Prepended elements appear in exact order at indices 0, 1, … before existing elements.

2. In-Place Prepend with Array.prototype.unshift() (When Mutation Is Intended)

When you intentionally want to mutate a local array in place—such as a local accumulator inside a loop or function scope—call arr.unshift(...newItems), which returns the updated array length:

// Prepend items in place using unshift() with explicit guard checks
function unshiftItemsInPlace(targetArray, newItems = []) {
  if (!Array.isArray(targetArray)) {
    throw new TypeError("Expected targetArray to be an Array.");
  }

  if (!Array.isArray(newItems)) {
    throw new TypeError("Expected newItems to be an Array.");
  }

  if (newItems.length === 0) {
    return targetArray.length;
  }

  return targetArray.unshift(...newItems);
}

// Example usage:
const localList = ["second", "third"];
const updatedLength = unshiftItemsInPlace(localList, ["first"]);
console.log(localList); // ["first", "second", "third"]
console.log("New length:", updatedLength); // 3
  • In-place mutation & length return: unshift() modifies localList directly and returns the new .length rather than the array itself.
  • Pass multiple items at once: unshift(a, b) prepends a then b in order ([a, b, ...]) in a single call.

3. Common Traps to Avoid

Prepending elements to a JavaScript array often runs into a few pitfalls:

  • Mutating shared state or props with .unshift(): Calling .unshift() on an array held in React/Vue/Redux state or passed into a function mutates it in place and can break change detection or caller expectations—prefer [...items, ...arr].
  • Expecting .unshift() to return the new array: .unshift() returns the new array length (a number), not the array—chaining .unshift(...).map(...) throws a TypeError.
  • Calling .unshift(arr) instead of .unshift(...arr) when prepending an array: Passing an array without spreading nests the entire array as a single element at index 0 ([[...], ...existing]).

TL;DR: Use [...newItems, ...arr] (or newItems.concat(arr)) to prepend elements without mutating arr, and use arr.unshift(...newItems) only when you intentionally want to mutate arr in place and receive its new length.