How To Add New Elements To A JavaScript Array

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 push() function that adds new items to the end of an array and returns the new length.

let colors = ["Red", "Blue", "Orange"];
console.log('Array before push: ' + colors);
// append new value to the array
colors.push("Green");
console.log('Array after push : ' + colors);
The new item(s) will be added only at the end of the Array.
You can also add multiple elements to an array using push().

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.

let colors = ["Red", "Blue", "Orange"];
console.log('Array before unshift: ' + colors);
// append new value to the array
colors.unshift("Black", "Green");
console.log('Array after unshift : ' + colors);

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.

let array1 = ["Red", "Orange", "Green"];
let array2 = ["Black", "Yellow"];
console.log('array1: ' + array1);
console.log('array2: ' + array2);
let arr = array1.concat(array2);
// append new value to the array
console.log('array: ' + arr);
The concat() 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 splice() method which can be used for appending or removing elements from an array.

let colors = ["Red", "Orange", "Green", "Blue"];
console.log('Array before splice: ' + colors);
colors.splice(2, 0, "Black", "Yellow");
// append new value to the array
console.log('Array after splice: ' + colors);

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 splice() 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.


Do you find this helpful?

Related articles