Appending an item to an array in JavaScript is easy. There’re 2 ways to do it. Either we can use the spread operator, or we can use the array instance’s push
method.
To use the spread operator, we can take the original array, spread it into a new array and put the new item at the end, and then we assign it back to the original array.
For instance, we can do that as follows:
let arr = [1, 2, 3];
arr = [...arr, 4];
In the code above, we declare the array with let
so that we can do the assignment after it.
Then we append the new array entry to it by using the spread operator and then add the new entry as we did in the 2nd line and assign it back to the original array.
Now arr
is [1, 2, 3, 4]
.
The other way is to call the push
method which appends the array item in place.
To do that, we can write:
const arr = [1, 2, 3];
arr.push(4);
Now we have the same result, but we don’t have to assign the modified array back to the original array as we did with the first example, so we can use const
to declare the array.
Appending an item to an array is easy with JavaScript.