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 Representation
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 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
- Google Chrome 1 and above
- Edge 12 and above
- Firefox 1 and above
- Opera 4 and above
- Safari 1 and above
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.