How to Push multiple Values to an Array in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 15 20212 min read

Push multiple Values to an Array #

To push multiple values to an array, call the push() method, passing it multiple, comma-separated values. The push method adds one or more values to the end of the array and returns the new length of the array.

index.js
const arr = ['a']; arr.push('b', 'c', 'd'); console.log(arr); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c', 'd']

The Array.push method takes one or more parameters to get added to the end of the array.

The method changes the contents of the original array and returns the array's new length.

Alternatively, you can use the spread operator (...), which is a bit more flexible.

index.js
let arr = ['a']; arr = [...arr, 'b', 'c', 'd']; console.log(arr); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c', 'd']

Notice that we declared the arr variable, using the let keyword. Had we declared the variable using const, we wouldn't be able to reassign it.

An easy way to think about the spread operator is that we unpack the values of one array into another.

In this particular scenario we unpack the contents of the arr array into a new array and add 3 more values to the end of the new array.

You can also use the Array.splice method to push multiple values to an array.

index.js
const arr = ['a']; arr.splice(arr.length, 0, 'b', 'c', 'd'); console.log(arr); // ๐Ÿ‘‰๏ธ ['a', 'b', 'c', 'd']

We pass the following parameters to the splice method:

  1. start index - the index at which to start changing the array
  2. delete count - how many elements we want to delete from the array, from the start index onwards
  3. one or more values to add to the array, from the start index onwards

Because we want to insert the elements at the end of the array, we pass the array's length as the start index.

We don't want to delete any elements, we pass 0 as the delete count.

This approach achieves the same result as the push method, however is a bit more verbose and indirect.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee