JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to use Array unshift() method in JavaScript?

JavaScript provides unshift() method to add elements to the beginning of an array. You can even add multiple elements and array to the beginning of the array using unshift() method.

Note: unshift() method modifies the original array and returns the length of the updated array.

let vegetables = ["Potato", "Tomato", "Cabbage"];
vegetables.unshift("Broccoli");
console.log(vegetables);

Output

["Broccoli", "Potato", "Tomato", "Cabbage"]

How to add multiple elements to the beginning of array in JavaScript?

You can pass multiple elements to unshift() method and those elements will be added to the beginning of the array.

let groceryList = ["Milk", "Bread", "Garlic"];
console.log(groceryList);
groceryList.unshift("Pasta", "Tomato Sauce");
console.log(groceryList);

Output

["Milk", "Bread", "Garlic"]
["Pasta", "Tomato Sauce", "Milk", "Bread", "Garlic"]

How to add array to the beginning of array in JavaScript?

You can pass array to unshift() method and that array will be added to the beginning of the array.

let arr = [1, 2, 3, 4];
console.log(arr);
arr.unshift([5, 6, 7]);
console.log(arr);

Output

[1, 2, 3, 4]
[[5, 6, 7], 1, 2, 3, 4]

Recommended Posts