How to use Unshift() Method In Javascript

The unshift() method is used to add one or more elements to the beginning of an array.

Example: This code example uses unshift() method to add the elements into an array.

Javascript




const myArray = [4, 5, 6];
  
myArray.unshift(3);
console.log(myArray);
  
myArray.unshift(1, 2);
console.log(myArray);


Output

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

Add Elements to a JavaScript Array

JavaScript Arrays are a fundamental data structure in JavaScript, providing a flexible way to store and manage collections of values. Add elements to a JavaScript Array is a common operation in programming. There are different methods to add elements to the JavaScript array, which are described below

Similar Reads

Methods to Add Elements to a JavaScript Array

Following are the methods that can be used to add elements to a JavaScript array:...

Method 1: Using Push() Method

The push() method is used to add one or more elements to the end of an array....

Method 2: Using concat() Method

...

Method 3: Using Splice() Method

The concat() method is used to create a new array by combining existing arrays with additional elements....

Method 4: Using Spread Operator

...

Method 5: Using Unshift() Method

The splice() method is used to add or remove elements from a specific index in an array. We need to set the second argument of the splice method to 0 for inserting elements into an array using it....

Method 6: Using Length Property

...

Method 7: Using Index Assignment

The Spread Operator is used to extend an array and create a new array with new elements....