JavaScript Array unshift() Method

JavaScript Array unshift() Method | The provided array can have one or more elements added to the beginning using the JavaScript Array unshift() Method. This function lengthens the existing array by the number of new elements added to the array.

Syntax:
array.unshift(element1, element2, …, elementX)

Parameters: This technique only takes one input.
element: The array’s initial element for this parameter is to be added.
Return value: After adding the arguments to the array’s beginning, this function returns the array’s new length.

Let’s look at a few examples of the JavaScript array unshift() method by adding one or more than one element in an existing array.

JavaScript Array unshift() Method Example

1) Adding an element to an array using the JavaScript Array unshift() technique.

The unshift() technique is used in the example below to include the number 10 in the numbers array:-

let numbers = [30, 40];
const length = numbers.unshift(20);

console.log({ length });
console.log({ numbers });

Output:-

{ length: 3 }
{ numbers: [ 20, 30, 40 ] }

The new element 20 is added at the 0th index of the array and the size of the array becomes 3. We can also insert more than one element at a time by using unshift() method. All the elements passed in unshift() method will be placed at the beginning of the existing array.

2) Adding many elements to an array using the JavaScript Array unshift() technique.

The unshift() method is used in the example below to start an array with two additional elements:

let numbers = [60, 80, 100];
const length = numbers.unshift(20, 40);

console.log({ length });
console.log({ numbers });

Output:-

{ length: 5 }
{ numbers: [ 20, 40, 60, 80, 100 ] }

3) Adding elements from one array to another array using JavaScript array unshift() method.

The unshift() method is used in the example below to add elements from one array to the start of another array.

let days = ["Mon", "Tue", "Wed", "Thu", "Fri"];
let weekends = ["Sat", "Sun"];

for (const weekend of weekends) {
  days.unshift(weekend);
}

console.log(days);

Output:-

[ ‘Sun’, ‘Sat’, ‘Mon’, ‘Tue’,, ‘Wed’, ‘Thu’, ‘Fri’ ]

If you want to insert one or more elements at the beginning of an array, use the JavaScript array unshift() method. We can also use the array-like object with the unshift() function by using the call() or apply() methods.

Similar to unshift() method, JavaScript also contains the shift() method which can be used to remove elements from the beginning of the array. Also see:- JavaScript Remove First Element From Array

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *