JavaScript Array.unshift() Method
-
Syntax of JavaScript
array.unshift()
: -
Example Code: Use the
array.unshift()
Method to Add New Elements at the Beginning of a Given Array -
Example Code: Use the
array.unshift()
Method to Add Elements of Another Array in an Array
In JavaScript, the array.unshift()
method adds a new element at the start of an array and increases its actual length. Users can also add the elements of another array into the given array using the array.unshift()
method.
Syntax of JavaScript array.unshift()
:
refarray.unshift("el1", "el2");
refarr2.unshift("refarr1");
Parameters
el1 , el2 , eln |
These are the elements to be added at the beginning of an array. A minimum of one element is required. |
refarr1 |
To add the elements of an array at the beginning of the refarr2 array. |
Return
This method returns the new array length.
Example Code: Use the array.unshift()
Method to Add New Elements at the Beginning of a Given Array
In JavaScript, we can use the array.unshift()
method to add new elements at the beginning of a given array. The actual length of the array can change depending on the number of elements added using this method.
In this example, we used the array.unshift()
method to add new elements and get the new length of the array.
let array = ["Java","C++"];
let refunshift = array.unshift("Python","JavaScript");
console.log(array);
console.log(refunshift);
Output:
[ 'Python', 'JavaScript', 'Java', 'C++' ]
4
Example Code: Use the array.unshift()
Method to Add Elements of Another Array in an Array
Users can append the elements of another array at the beginning of a current array using the array.unshift()
method.
In the example below, we have created two arrays, arr1
and arr2
, with different elements and used the array.unshift()
method to add the elements of the arr2
array into arr1
.
Also, users can see the length of the updated array in the output. It adds the whole array as a single element in another array.
const arr1 = ["File3"];
let arr2 = ["File1", "File2"];
arr1.unshift(arr2);
console.log(arr1);
console.log(arr1.length);
Output:
[ [ 'File1', 'File2' ], 'File3' ]
2
The array.unshift()
method adds new elements to a reference array at the beginning. Users can also append the whole another array in the reference array using this method.