Fri Oct 15 2021·2 min read
Photo by Jason Blackeye
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.
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.
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.
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.
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
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.
I'll send you 1 email a week with links to all of the articles I've written that week