In this article, you will learn about the Javascript Array built-in method Array.prototype.unshift()
. How does this method work in javascript?
This Array.prototype.unshift()
method is used to add one or more elements at the beginning of the given array and returns the new length of the array.
array.unshift(element1, element2, …,elementN);
This method takes no. of N elements as a parameter to create an array as given below:
Here are some examples of Array.prototype.unshift()
method:
const arr = [1, 2];
console.log(arr.unshift(0));
// result of the call is 3, which is the new array length
console.log(arr);
// Final Array => [0, 1, 2]
console.log(arr.unshift(-2, -1));
// the new array length is 5
console.log(arr);
// Final Array => [-2, -1, 0, 1, 2]
console.log(arr.unshift([-4, -3]));
// the new array length is 6
console.log(arr);
// Final Array => [[-4, -3], -2, -1, 0, 1, 2]
console.log(arr.unshift([-7, -6], [-5]));
// the new array length is 8
console.log(arr);
// Final Array => [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ]
I hope this article will help you to understand the javascript Array built-in method Array.prototype.unshift().
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments