JavaScript Array unshift() Method

JavaScript array unshift() method is “used to add new elements to the beginning of an array and returns the new length of the array.”

Syntax

array.unshift(item1, item2, ..., itemX)

Parameters

item: The elements to add to the front of the array.

Return value

This function returns the new length of the array after inserting the arguments at the beginning of the array.

Example 1: How to Use Array shift() function

let apps = ["Instagram", "Facebook", "Messanger"];
apps.unshift("Oculus", "WhatsApp");

console.log(apps);

Run the file, and you can see that Oculus and WhatsApp are appended at the start of an array.

Output

Javascript Array Unshift Example | Array.prototype.unshift() Tutorial

Example 2: Using array.unshift() method with Object

const objA = {
  name: 'Millie Bobby Brown'
}
const objB = {
  name: 'Finn Wolfhard'
}
const objC = {
  name: 'Sadie Sink'
}

let arr = [objA, objB];
arr.unshift(objC);

console.log(arr);

Output

[ { name: 'Sadie Sink' }, 
  { name: 'Millie Bobby Brown' }, 
  { name: 'Finn Wolfhard' } ]

Example 3: Adding multiple elements using unshift() method

We can add multiple elements to the start of an array using the unshift() method.

const objA = {
  name: 'Millie Bobby Brown'
}
const objB = {
  name: 'Finn Wolfhard'
}
const objC = {
  name: 'Sadie Sink'
}
const objD = {
  name: 'Noah Schnapp'
}
const objE = {
  name: 'Gaten Matterazo'
}

let arr = [objA, objB];
arr.unshift(objC, objD, objE);
console.log(arr);

Output

[ { name: 'Sadie Sink' }, 
  { name: 'Noah Schnapp' }, 
  { name: 'Gaten Matterazo' }, 
  { name: 'Millie Bobby Brown' }, 
  { name: 'Finn Wolfhard' }
]

Example 4: Calling unshift() on non-array objects

The unshift() method reads the length property of this. It then shifts all properties in the range 0 to length – 1 right by the number of arguments and sets each index starting at 0 with the arguments passed to unshift().

const arrayLike = {
  length: 3,
  0: 11,
  1: 19,
  2: 21,
};

Array.prototype.unshift.call(arrayLike, 1, 2);
console.log(arrayLike);

Output

{ '0': 1, '1': 2, '2': 11, '3': 19, '4': 21, length: 5 }

Browser Compatibility

  1. Google Chrome 1 and above
  2. Edge 12 and above
  3. Firefox 1 and above
  4. Internet Explorer 5.5 and above
  5. Opera 4 and above
  6. Safari 1 and above

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.