Array.prototype.unshift()

unshift(...items)
Returns: number · Updated March 13, 2026 · Array Methods
array unshift mutator

unshift() adds one or more elements to the beginning of an array and returns the new length. It modifies the array in place, shifting existing elements to higher indices.

Syntax

arr.unshift(element1)
arr.unshift(element1, element2)
arr.unshift(element1, element2, /* ... */ elementN)

Parameters

ParameterTypeDefaultDescription
itemsanyElements to add to the beginning of the array

Examples

Basic usage

const colors = ["blue", "green"];
colors.unshift("red");

console.log(colors);
// ["red", "blue", "green"]

Adding multiple elements

const nums = [3, 4, 5];
const newLength = nums.unshift(1, 2);

console.log(nums);      // [1, 2, 3, 4, 5]
console.log(newLength);  // 5

Using unshift with zero arguments

const arr = [1, 2, 3];
const length = arr.unshift();
console.log(length); // 3 (no change)

Common Patterns

Prepending elements

const users = ["charlie", "diana"];
users.unshift("alice", "bob");

console.log(users);
// ["alice", "bob", "charlie", "diana"]

Implementing a priority queue

class PriorityQueue {
  constructor() {
    this.items = [Global_Objects::eval];
  }
  
  enqueue(item, priority) {
    // Simple implementation: higher priority = earlier position
    const entry = { item, priority };
    let added = false;
    
    for (let i = 0; i < this.items.length; i++) {
      if (priority > this.items[i].priority) {
        this.items.splice(i, 0, entry);
        added = true;
        break;
      }
    }
    
    if (!added) {
      this.items.push(entry);
    }
  }
  
  dequeue() {
    return this.items.shift().item;
  }
}

const pq = new PriorityQueue();
pq.enqueue("low priority", 1);
pq.enqueue("high priority", 10);
pq.enqueue("medium priority", 5);

console.log(pq.dequeue()); // "high priority"
console.log(pq.dequeue()); // "medium priority"
console.log(pq.dequeue()); // "low priority"

Behavior Notes

  • unshift() accepts zero arguments, which returns the current length without changes
  • This method modifies the original array (mutating method)
  • All existing elements shift up by the number of elements added

See Also