The unshift() method is used to add one or more elements to the beginning of an array.

  • Adds elements to the start (index 0) of an array
  • Modifies the original array
  • Returns the new length of the array
  • Slower than push() for large arrays (because elements are re-indexed)

1.Syntax

array.unshift(element1, element2, ..., elementN);

2.Basic Example

let fruits = ["Banana", "Mango"];

fruits.unshift("Apple");

console.log(fruits);
// ["Apple", "Banana", "Mango"]

3.Add Multiple Elements

let numbers = [3, 4];

numbers.unshift(1, 2);

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

4.Return Value of unshift()

let colors = ["Green", "Blue"];
 let newLength = colors.unshift("Red"); console.log(newLength); // 3 console.log(colors); // ["Red", "Green", "Blue"]

5.Unshift Objects into an Array

let users = [];

users.unshift({
name: "Zaman",
role: "Admin"
});

console.log(users);

6.Using unshift() in a Loop

let reversed = [];
let original = [1, 2, 3, 4];
for (let i = 0; i < original.length; i++) { reversed.unshift(original[i]); } console.log(reversed);
// [4, 3, 2, 1]

Categorized in:

Javascript Array Methods,