Get my new tutorials in your inbox every week

What is unshift() in JavaScript?

What is unshift() in JavaScript?

We have heard about Array push and pop methods and how they can be used to add or remove elements from the end of an array. JavaScript provides two more useful methods – unshift and shift to add or remove elements at the start of an array. Today we are going to look at what is unshift in JavaScript and how we can use it.

What is unshift?

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

var arr = []; //an array
arr.unshift(element); //returns the new length of the array

The original array is modified.

Examples

I have defined a JavaScript array below,

var arr = [3,4,5,6];

Let’s add a few elements to the start of the Array.

Adding one element,

//add 2 to the start 
arr.unshift(2); //returns 5, i.e the new length
console.log(arr); //[2,3,4,5,6]

Adding multiple elements together,

var arr = [3,4,5,6];

arr.unshift(1,2,9,10); //returns 8
console.log(arr); //[1, 2, 9, 10, 3, 4, 5, 6]

You can keep adding n number of elements. No stopping you!

Can I rather add an Array? Let’s try it

var arr = [3,4,5,6];

//let's insert an array
arr.unshift([1,2]); //returns 5
console.log(arr); //[[1,2], 3, 4, 5, 6]

//so the entire arr is inserted to the start
//another example
var arr = [3,4,5,6];
arr.unshift([1,2], [9]); // returns 6
console.log(arr); // [[1,2], [9], 3, 4, 5, 6]

Browser Support

It’s supported in all major desktop and mobile browsers (since IE6+, Firefox 2+, Chrome 1+, etc). So, completely safe to use it, and no worries.

If you still want to check the support table, have a look at the caniuse table.


Write a Comment

Your email address will not be published. Required fields are marked *