JavaScript Array.unshift() Method

Shubham Vora Jan 30, 2023
  1. Syntax of JavaScript array.unshift():
  2. Example Code: Use the array.unshift() Method to Add New Elements at the Beginning of a Given Array
  3. Example Code: Use the array.unshift() Method to Add Elements of Another Array in an Array
JavaScript Array.unshift() Method

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.

Author: Shubham Vora
Shubham Vora avatar Shubham Vora avatar

Shubham is a software developer interested in learning and writing about various technologies. He loves to help people by sharing vast knowledge about modern technologies via different platforms such as the DelftStack.com website.

LinkedIn GitHub

Related Article - JavaScript Array