JavaScript Array unshift() Method

The array unshift() is a built-in JavaScript function that adds elements to the beginning of the array and returns the new length of the array. It takes several arguments, the same as the number of elements to be added, and changes the array’s length.

Syntax

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

Parameters

The number of arguments to this function is the same as the number of elements added at the beginning 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

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

The following code will include almost all the scenarios of the unshift() method.

Example 2

let arr = [1, 2];

arr.unshift(0); // result of call is 3, the new array length
// arr is [0, 1, 2]

arr.unshift(-2, -1); // = 5
// arr is [-2, -1, 0, 1, 2]

arr.unshift([-3]);
// arr is [[-3], -2, -1, 0, 1, 2]

Example 3

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 4

We can add multiple items 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' }
]

That’s it.

1 thought on “JavaScript Array unshift() Method”

Leave a Comment

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