You are currently viewing 3 Methods to Add New Element to Beginning of Array in JavaScript

3 Methods to Add New Element to Beginning of Array in JavaScript

Add Element to Beginning of Array JavaScript

There are several ways to add new element to the beginning of an array in JavaScript like using the spread operator, unshift() method, and concat() method. So, in this article, we will explore this in detail.

3 Simple Ways to add element to an Array

These are the easiest and most popular methods to add a new element at the beginning of the array.

1. Using the spread operator:

The spread operator indicates three dots like (…). We can use this method to add one or more elements to an array. It creates a new array and does not modify the original array.

let myStr = ['b', 'c', 'd'];
let newArray = ['a', ...myStr];
console.log(newArray);


// Output: ['a', 'b', 'c', 'd']

In this code:

  • We have created the array ‘myStr’ with 3 elements.
  • If you want to add the element, you need to create a new array ‘newArray’ that includes the element ‘a’, followed by the spread operator (…) and the ‘myStr’ array.
  • Then we logged the array ‘myArray’ and it includes the element ‘a’ at the beginning.

2. Using the unshift() method

It is one of the easiest methods to add a new element at the beginning of the array. The unshift() method adds a new element by modifying the original array.

let myStr = ['b', 'c', 'd'];

myStr.unshift('a');
console.log(myStr);

// Output: ['a', 'b', 'c', 'd']

In this code:

  • We use the unshift() method to add the element at the beginning by passing the parameter as new element ‘a’ of the array ‘myStr’.
  • Now the array ‘myStr’ have the element ‘a’ at the beginning.
READ ALSO  Reserved Words in JavaScript | Explained

3. concat() method:

We can create a new array that includes the element we want to add, followed by the concat() method and the original array. Here’s an example:

let myStr = ['b', 'c', 'd'];

let newArray = ['a'].concat(myStr);
console.log(newArray);

// Output: ['a', 'b', 'c', 'd']
  • In this example, we create a new array called newArray that includes the element ‘a’, followed by the concat() method and the ‘myStr ‘ array.
  • Now, the ‘myArray’ array has the new element and ‘myStr’ elements.

Conclusion

So, using these methods we can add the new array element to the beginning easily in javascript. I recommend the 2nd method i.e. using unshift() method because it is adding a new element by modifying the original array others are not.

Leave a Reply