References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript array.unshift() method

Method JavaScript All modern browsers Updated
Quick answer

The unshift() method adds one or more elements to the start of an array and returns the new length. const a = [2, 3]; a.unshift(1) makes a become [1, 2, 3]. It's the front-of-the-array version of push(), and it mutates the array in place.

Overview

unshift() prepends elements — it adds them to the beginning of an array, pushing everything else along. It's the counterpart to push() (which appends to the end) and the partner of shift() (which removes from the front). Like push(), it returns the new length, not the array.

If you pass several values, they're added in the order you wrote them: arr.unshift(1, 2) puts 1 then 2 at the front, so they end up as the first two elements. The method mutates the array in place.

For an immutable alternative — a new array rather than a mutation — the spread operator is cleaner: [newItem, ...arr] builds a fresh array with the item at the front, which is what you'd reach for in React state. And like shift(), unshift() is O(n) because existing elements must be re-indexed.

Syntax

const newLength = array.unshift(element1)
const newLength = array.unshift(element1, element2)

[2, 3].unshift(0, 1)  // array becomes [0, 1, 2, 3]

Parameters

The array.unshift() method accepts the following parameters.

Parameter Description
element1 ... elementN One or more values to add to the start of the array, in the order given.

Example

Live example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
  const list = ['banana', 'cherry'];

  const len = list.unshift('apple');

  document.getElementById('out').textContent =
    'array:  ' + list.join(', ') + '\n' +
    'length: ' + len; // array: apple, banana, cherry / length: 3
</script>

Best practices

  • Remember it returns the new length, not the array.
  • Add several items in one call — they keep the order you pass them.
  • For a new array instead of a mutation, use the spread syntax [item, ...arr].
  • Use push() to add to the end; unshift() adds to the front.

Frequently asked questions

What does unshift() do?
It adds one or more elements to the beginning of an array and returns the array's new length.
What is the difference between unshift() and push()?
unshift() adds to the front; push() adds to the end. Both mutate the array and return the new length.
How do I add to the start without mutating the array?
Use the spread operator: const next = [newItem, ...arr] creates a new array with the item at the front.
Does unshift() return the array?
No — it returns the new length. Read the array variable itself to see the result.