In JavaScript, to add to an array, we can simply use the JavaScript Array push() method. The push() method will add an element to the end of the array.

var numArray = [1, 2, 3];

numArray.push(4);

console.log(numArray);

#Output:
[1, 2, 3, 4]

You can also use the push() method to add multiple elements to an array.

var numArray = [1, 2, 3];

numArray.push(4,5);

console.log(numArray);

#Output:
[1, 2, 3, 4, 5]

When working with collections of data in JavaScript, the ability to easily add items or change the collection is important.

One such case where you may want to modify a collection is if you want to add elements to an array in JavaScript.

To add on item to an array in JavaScript, you can use the push() method. The push() method will add an element or elements to the end of the array.

Below shows a simple example of how you can use the push() method to add an item to an array in JavaScript.

var numArray = [1, 2, 3];

numArray.push(4);

console.log(numArray);

#Output:
[1, 2, 3, 4]

Adding Multiple Items to an Array in JavaScript

If you want to add multiple items to an array in JavaScript, then you could use the push() method and include multiple items in it.

Below shows you how to add multiple elements to an array using the push() method in JavaScript.

var numArray = [1, 2, 3];

numArray.push(4,5,6,7);

console.log(numArray);

#Output:
[1, 2, 3, 4, 5, 6, 7]

Adding Multiple Items to an Array in JavaScript with the Spread Operator (…)

If you want to add multiple items to an array in JavaScript, then we could also use the Spread Operator (…).

Below shows you how to add multiple elements to an array using Spread Operator (…) in JavaScript.

var numArray = [1, 2, 3];

var arr1 = [4,5];
var combinedArray1 = [ ...numArray, ...arr1 ];

console.log(combinedArray1);

var arr2 = [6,7];
var combinedArray2 = [ ...combinedArray1, ...arr2 ];

console.log(combinedArray2);

#Output:
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7]

Hopefully this article has been useful for you to learn how to use JavaScript to add to an array.

Categorized in:

JavaScript,

Last Update: March 11, 2024