Push multiple Values to an Array in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Push multiple Values to an Array in JavaScript #

Use the Array.push() method to push multiple values to an array, e.g. arr.push('b', 'c', 'd');. The push() method adds one or more values to the end of an 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 arguments and adds them to the end of the array.

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

Note that the push() method does not return the array, it returns the array's new length.

Alternatively, you can use the spread syntax (...).

Push multiple Values to an Array using spread syntax #

Use the spread syntax to push multiple values to an array, e.g. arr = [...arr, 'b', 'c', 'd'];. The spread syntax can be used to unpack the values of the original array followed by one or more additional values.

index.js
let arr = ['a']; arr = [...arr, 'b', 'c', 'd']; console.log(arr); // 👉️ ['a', 'b', 'c', 'd']

Notice that we used the let keyword to declare the arr variable. 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.

Alternatively, you can use the splice() method.

Push multiple Values to an Array using splice() #

Use the Array.splice() method to push multiple values to an array, e.g. arr.splice(arr.length, 0, 'b', 'c', 'd');. The splice() method will add the provided values to the end of the array.

index.js
const arr = ['a']; arr.splice(arr.length, 0, 'b', 'c', 'd'); console.log(arr); // 👉️ ['a', 'b', 'c', 'd']

We passed the following arguments to the Array.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

We want to insert the elements at the end of the array, so we passed the array's length as the start index.

We don't want to delete any elements, so we supplied 0 for the delete count argument.

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

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.