How to add elements into an array in JavaScript

How to add elements into an array in JavaScript

Posted by

In this guide, Let’s discuss four different methods of add elements into an array in JavaScript.

JavaScript Array Description

In JavaScript, Array is a special variable that is used to store different values. It is usually used when we want to store the list of values and access them by a single variable. In Most languages, Array is a reference to the multiple variables, while in JavaScript array is a single variable that stores multiple elements.

JavaScript Array can be modified even after it has been declared and initialized. It can have multiple element types stored in it. JavaScript arrays offer a whole bunch of built-in methods we can take advantage of. They are dynamic and easy to use.

Here’s a list of the four methods which are used to add elements into an array in JavaScript.

1. push() 2. unshift() 3. concat() 4. splice()

1. The Push Method

The first and probably the most common “push() “method allows you to add one or more elements to the end of an array. It revises the array and returns the new length of the array.

The following shows how to add a single new element to an existing array:

2. The Unshift Method

The second “unshift()” method allows you to add elements to the beginning of an array. It accepts numerous arguments, modifies the indexes of existing elements, and returns the new length of the array. The unshift method adjusts the array on which it is invoked.

3. The Concat Method

The concat() method does not actually add elements to the existing array. concat() creates a new modified array. Both the unshift() and push() methods return the length of the new array. On the other hand, concat(), will return a completely new array.

The concat() method can be used to add elements to both the beginning and end of the array. This method is valuable when we need the first array in its initial state.

4. The splice() Method

splice()  method is a bit different from the other methods. It is used to get rid of or insert elements in an array. It needs three different arguments. 

Argument 1 – where the item is going to be added to the array. 

Argument 2 – specifies the number of elements/items that are to be removed from the array. In the case of adding elements value will be 0. 

Argument 3 – contains the values of the elements/items that are to be added.

Conclusion

In this guide, we saw all four different ways of adding elements to an array in JavaScript. use push() If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat(). If you do not want to modify the original then use the concat() method. Regardless, the splice() method delivers you the most power over the index at which we want to add our new elements.

Leave a Reply

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