What is unshift?
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.
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], ); // returns 6 console.log(arr); // [[1,2], , 3, 4, 5, 6]
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.
If you enjoyed this post and want similar articles to be delivered to your inbox directly, you can subscribe to my newsletters. I send out an email every two weeks with new articles, tips & tricks, news, free materials. No spamming, of course.