JavaScript Array unshift() Method

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

It modifies the original array.

Syntax

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

Parameters

item1,item2: The elements to add to the front of the array.

Return value

Returns the new length of the array.

Visual RepresentationVisual Representation of JavaScript Array unshift() Method

Example 1: How to Use Array unshift() Method

let apps = ["Insta", "Fb", "x"]; 

//before length
console.log(apps.length);

apps.unshift("Snap", "WhatsApp"); 
console.log(apps);

//After length
console.log(apps.length);

Output

3
[ 'Snap', 'WhatsApp', 'Insta', 'Fb', 'x' ]
5

Example 2: Using 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

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: Using an empty arrayVisual Representation of Using an empty array

let arr = [];

console.log(arr.unshift("A", "B"));
console.log(arr);

Output

2
[ 'A', 'B' ]

Example 5: Passing non-array objects

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. Opera 4 and above
  5. Safari 1 and above

Leave a Comment

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