Menu
Coddy logo textTech

Shift & Unshift

Lesson 7 of 18 in Coddy's Array Methods in JavaScript course.

The shift() method removes the first element from an array and returns the removed element. It modifies the original array by decreasing its length.

  • Imagine an array as a line of elements. shift() takes the element at the front (index 0) and removes it, shifting all remaining elements one position to the left.
  • It's useful when you need to process or store the first element separately and then work with the remaining elements. For example :
const fruits = ["apple", "banana", "orange", "mango"];
const firstFruit = fruits.shift();

console.log(fruits); // Output: ["banana", "orange", "mango"]
console.log(firstFruit); // Output: "apple"

After using the shift() method on the fruits array in the above example, it removes the first element "apple" from the array.


The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array. It modifies the original array by increasing its length.

  • Think of unshift() as inserting elements at the front of the line. The new elements become the first elements, shifting existing elements to the right.
  • This method is handy when you want to prepend new items to an array or reorder elements. For example :
const colors = ["red", "green", "blue"];
const newColors = colors.unshift("yellow", "purple");

console.log(colors); // Output: ["yellow", "purple", "red", "green", "blue"]
console.log(newColors); // Output: 5 (the new length)

After using the unshift() method on the colors array in the above example, it inserts the elements "yellow" and "purple" at the beginning of the array.

challenge icon

Challenge

Easy

You are given a to-do list with three tasks: "Read a book",  "Play sports" and “Wash dishes” as listed in the given tasks array.

Write JavaScript code to remove the first task from the to-do list, add a new task "Feed the cat" in its place, and then log the updated to-do list.

Try it yourself

let tasks = ['Read a book', 'Play sports', 'Wash dishes'];

// Write code here

All lessons in Array Methods in JavaScript