Learn a couple of ways to append items to an array with JavaScript
To append an item to an array, you can either use JavaScript’s push()
method or the concat()
method, depending on the context. Both methods are provided by the JavaScript Array object.
I’ll show you how and why to use both methods in practice.
Append a single item to an array
Let’s append a vegetable to an existing list (array) of vegetables:
const vegetables = ["broccoli", "onion", "spinach"]
vegetables.push("carot")
Now you can print out the result:
console.log(vegetables)
// ["broccoli", "onion", "spinach", "carot"]
Note: the vegetables
array has been modified.
Append multiple items to an array
To append multiple items to an array, you can also use push()
, you just add multiple arguments, separated by commas:
const vegetables = ["broccoli", "onion", "spinach"]
vegetables.push("carot", "green beans", "kale")
Note: the vegetables
array has been modified.
Modify Array vs. New Array / push() vs. concat()
As noted above, the push()
method modifies the original array. If you instead want to create a new array based on the original, and append new item(s) to that, then use the JavaScript Array concat()
method:
const vegetables = ["broccoli", "onion", "spinach"]
const newVegetables = vegetables.concat("carot")
Now try to print out both variables:
console.log(vegetables)
// ["broccoli", "onion", "spinach"]
console.log(newVegetables)
// ["broccoli", "onion", "spinach", "carot", "green beans", "kale"]
And you can see that the original vegetables
array is unchanged, and newVegetables
contains a copy of the vegetables
array + the carot
we added to it with the concat()
method.
The concat()
method works the same with multiple items, you just separate them with commas, just like you did with the push()
example earlier:
const vegetables = ["broccoli", "onion", "spinach"]
const newVegetables = vegetables.concat("carot", "green beans", "kale")
In summary:
It’s important to not confuse the two array methods, so here’s a final reminder:
push()
modifies the original arrayconcat()
returns (creates) a new array