W3docs

How To Add New Elements To A JavaScript Array

To add new elements you can use the following JavaScript functions: push() unshift(), concat() function or splice(). See examples.

There are several methods for adding new elements to a JavaScript array. Let's define them.

push()

The push() method is an in-built JavaScript method that is used to add a number, string, object, array, or any value to the Array. You can use the <kbd class="highlighted">push()</kbd> function that adds new items to the end of an array and returns the new length.

Javascript array push element

javascript— editable
Info

The new item(s) will be added only at the end of the Array.

Tip

You can also add multiple elements to an array using <kbd class="highlighted">push()</kbd>.

unshift()

Another method is used for appending an element to the beginning of an array is the unshift() function, which adds and returns the new length. It accepts multiple arguments, attaches the indexes of existing elements, and finally returns the new length of an array.

Javascript array unshift element

javascript— editable

concat()

You also can use the concat() function, which merges two or more arrays. The concat method is one of the methods that is used to add elements to an array.

Javascript concat arrays elements

javascript— editable
Danger

The <kbd class="highlighted">concat()</kbd> method does not change the existing arrays, but returns a new array, containing the values of the joined arrays.

splice()

To insert elements in the middle of an array you can use the <kbd class="highlighted">splice()</kbd> method which can be used for appending or removing elements from an array.

Javascript array splice method

javascript— editable

In the example above, the first parameter (2) defines the position where new elements should be added (spliced in). The second parameter (0) defines how many elements should be removed. The other parameters ("Black", "Yellow") define the new elements to be added.

When you use the <kbd class="highlighted">splice()</kbd> method to add elements to an array, the second argument would be zero. The third and subsequent arguments are elements that should be added to the Array.