Table of Contents
Introduction to JavaScript unshift()
Method
The unshift
method is a built-in method of the Array prototype in JavaScript that is used to add one or more elements to the beginning of an array. This method modifies the array on which it is called, and it returns the new length of the array.
In this article, we will discuss how to use the unshift
method in JavaScript.
Using the JavaScript unshift()
Method
Let’s work with the unshift
method across different examples. Here is an example of how to use the unshift
method to add an element to the beginning of an array:
let myArray = [1, 2, 3];
myArray.unshift(0);
console.log(myArray);
Output
[ 0, 1, 2, 3 ]
In this example, the unshift
method is called on the myArray
array, and it is passed the value "0" as its argument. This adds the value "0" to the beginning of the array, shifting the other elements of the array to the right. The unshift
method then returns the new length of the array (4), and the modified array is logged to the console.
In addition to adding a single element to the beginning of an array, the unshift
method can also be used to add multiple elements at once. For example:
let myArray = [1, 2, 3];
myArray.unshift(-1, 0);
console.log(myArray);
Output
[ -1, 0, 1, 2, 3 ]
In this example, the unshift
method is called on the myArray
array, and it is passed two values as arguments: "-1
" and "0
". This adds the two values to the beginning of the array, shifting the other elements of the array to the right. The unshift
method then returns the new length of the array (5), and the modified array is logged to the console.
Summary
The unshift
method is a built-in method of the Array prototype in JavaScript that is used to add one or more elements to the beginning of an array. This method modifies the array on which it is called, and it returns the new length of the array. The unshift
method is useful for adding elements to the beginning of an array, and it is often used in conjunction with other array methods, such as shift
and splice
, to manipulate the elements of an array.
References
Array.prototype.unshift() - JavaScript | MDN (mozilla.org)