Skip to main content

What does unshift() do?

The unshift() method in JavaScript does the opposite of what shift() does: it adds one or more elements to the beginning of an array and returns the new length of the array.


Example:

javascript
const fruits = ["banana", "cherry"]; const newLength = fruits.unshift("apple"); console.log(fruits); // ["apple", "banana", "cherry"] console.log(newLength); // 3
  • Elements are added to the beginning of the array (at index 0).
  • All existing elements shift to the right.
  • The method mutates the original array.
  • Returns the new length of the array, not the array itself.

You can add several elements at once:

javascript
const numbers = [3, 4]; numbers.unshift(1, 2); console.log(numbers); // [1, 2, 3, 4]

How it works

  1. Creates space at the beginning of the array.
  2. Shifts all current elements to new indices.
  3. Inserts the new values at positions starting from 0.
  4. Updates the length property.

Comparison with other methods

MethodWhat it doesWhere it adds / removesWhat it returnsMutates the array
push()Adds an elementTo the endNew lengthYes
pop()Removes an elementFrom the endRemoved elementYes
unshift()Adds an elementTo the beginningNew lengthYes
shift()Removes an elementFrom the beginningRemoved elementYes

Usage example (queue)

javascript
const queue = []; queue.unshift("first"); queue.unshift("second"); console.log(queue); // ["second", "first"]

It can be used to add elements to the front of a queue, when you need to work in a FIFO (First In - First Out) style.


Short version:

ActionDescription
arr.unshift(value1, value2, ...)Adds element(s) to the beginning
ReturnsThe new length of the array
Mutates the arrayYes
Example[2, 3].unshift(1) -> [1, 2, 3]

Conclusion: unshift() is a method for adding elements to the beginning of an array, with automatic shifting of all indices and an updated length.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.