How to Add an Element to JavaScript Array?

There are 3 methods to add elements to the JS array easily. Even though there are more than 3 methods to append items to the JavaScript array, I suggest you only these methods for completing the tasks more efficiently.

1. Using Push Method ( For Adding Single Items )

Every JavaScript array has built-in methods for various array operations. We can use the array push() method to add elements to an existing array. We can add as many items as we want at once by using this method.

Example 1

Here, I added an item to the existing array.

var pl= [1, 2, 3];
pl.push(4); // adding one item
console.log(pl); // Array(4) [ 1, 2, 3, 4 ]

Example 2

I added two items at once to the existing JS array.

var pl= [1, 2, 3];
pl.push(4, 5); // adding two items
console.log(pl); // Array(5) [ 1, 2, 3, 4, 5 ]

Example 3

This method is useful when you want to add an array to the existing array. It updates the existing array with items of the second array. The … operator is used to add an array.

const array1 = [1, 2];
const array2 = [3, 4];
array1.push(...array2);
console.log(array1); // Array(4) [ 1, 2, 3, 4 ]

2. Using Concat() Method ( for Creating a New Array )

If you don’t wish to change the values of an existing array, you can use the concat() method to add items to an array and create a new array from those values. The method will create a new array and add items.

Example 1: Adding Items

const array1 = [1, 2];
const array2 = array1.concat(3);
console.log(array1); // Array [ 1, 2 ]
console.log(array2); // Array(3) [ 1, 2, 3 ]

Example 2: Adding Two Arrays

const array1 = [1, 2];
const array2 = [3, 4];
const array3 = array1.concat(...array2);
console.log(array3); // Array(4) [ 1, 2, 3, 4 ]

3. Using … Operator to Combine Multiple Arrays

This last method is very helpful to combine multiple arrays and create a new array from them.

Example

const array1 = [1, 2];
const array2 = [3, 4];
const array3 = [...array1, ...array2];
console.log(array3); // Array(4) [ 1, 2, 3, 4 ]

Conclusion

All three methods are very helpful for adding multiple values to an existing array. You may use any one of the methods you wish without any doubt.