JS-057
unshift() explained in a JavaScript learning illustration — Add to the beginning of an array
Beginner4 min~4 min read#array#unshift#arrays

unshift()

Add to the beginning of an array

Goal

Learn to add new elements to the beginning of an array using unshift().

Explanation

  • unshift() adds a new element to the beginning of an array.
  • The existing elements shift to the right.
  • The method changes the original array.
  • It works with the beginning of an array.
  • unshift() is the opposite of shift().

Analogy

Imagine a line of people. unshift() places a new person at the very beginning of the line.

Code

const fruits = [
  "Banana",
  "Orange"
];

fruits.unshift("Apple");

console.log(fruits);

Result: ["Apple", "Banana", "Orange"]

Common mistake

Beginners often confuse unshift() with push(). unshift() adds to the beginning, while push() adds to the end.

Remember

  • unshift() adds an element to the beginning.
  • It works with the first element of an array.
  • It changes the original array.

Quick Quiz

Where does unshift() add an element?

Resources