The unshift() method of the Array class in JavaScript adds one or more elements to the front of an array and returns the new length of the array.
There are 4 variations for the syntax of Array.unshift() method. They are:
unshift()
This method adds no elements to the array and returns the new length of the array.
Returns value of type Number
.
unshift(element1)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
element1 | required | The first element to add to the front of the array. |
This method adds one element to the front of the array and returns the new length of the array.
Returns value of type Number
.
unshift(element1, element2)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
element1 | required | The first element to add to the front of the array. |
element2 | required | The second element to add to the front of the array. |
This method adds two elements to the front of the array and returns the new length of the array.
Returns value of type Number
.
unshift(element1, element2, /* …, */ elementN)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
element1 | required | The first element to add to the front of the array. |
element2 | required | The second element to add to the front of the array. |
elementN | optional | Additional elements to add to the front of the array. |
This method adds one or more elements to the front of the array and returns the new length of the array.
Returns value of type Number
.
In JavaScript, we can use the unshift() method to add one element to the front of an array and return the new length of the array.
For example,
const arr = [2, 3, 4];
const newLength = arr.unshift(1);
console.log(newLength); // Output: 4
console.log(arr); // Output: [1, 2, 3, 4]
4 [1, 2, 3, 4]
We can use the unshift() method to add multiple elements to the front of an array and return the new length of the array.
For example,
const arr = ['c', 'd'];
const newLength = arr.unshift('a', 'b');
console.log(newLength); // Output: 4
console.log(arr); // Output: ['a', 'b', 'c', 'd']
4 ['a', 'b', 'c', 'd']
We can use the unshift() method to add elements to the front of an empty array and return the new length of the array.
For example,
const arr = [];
const newLength = arr.unshift(1, 2, 3);
console.log(newLength); // Output: 3
console.log(arr); // Output: [1, 2, 3]
3 [1, 2, 3]
In this JavaScript tutorial, we learned about unshift() method of Array: the syntax and few working examples with output and detailed explanation for each example.