Course contentsShow
← JavaScript
Lesson 812 of 2,72319. ArraysFree lesson

unshift() and shift(): Adding and Removing from the Start

Add elements to the beginning with unshift() and remove the first element with shift().

unshift() and shift(): Adding and Removing from the Start

You'll learn how to add and remove elements at the beginning of an array using two mutating methods.

While push() and pop() work with the end of an array, JavaScript provides unshift() and shift() for working with the start. These methods modify the original array, just like their end-focused counterparts.

Adding to the Start with unshift()

The unshift() method adds one or more elements to the beginning of an array and returns the new length:

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

console.log(colors);      // ['red', 'green', 'blue']
console.log(newLength);   // 3

You can add multiple elements at once:

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

Removing from the Start with shift()

The shift() method removes the first element and returns it. All remaining elements shift down by one index:

const fruits = ['apple', 'banana', 'cherry'];
const removed = fruits.shift();

console.log(removed);  // 'apple'
console.log(fruits);   // ['banana', 'cherry']

If the array is empty, shift() returns undefined:

const empty = [];
console.log(empty.shift());  // undefined

Think of It Like a Queue

Imagine a line of people waiting: unshift() adds someone to the front of the line (cutting!), while shift() removes the person at the front. This is the opposite of push() and pop(), which work with the back of the line.

Key Takeaway: Use unshift() to add elements to the beginning of an array and shift() to remove the first element—both methods mutate the original array and affect all existing element indices.