Add Item to Array in JavaScript
- 1 minute read
There are a few ways to add an item to an array in JavaScript.
This is the most common method, which adds a given item to the end of a given array:
const array = [1, 2, 3];
const item = 4;
array.push(item);
The below snippet has the same functionality but is typically significantly more performant:
const array = [1, 2, 3];
const item = 4;
array[array.length] = item;
You can also use the unshift method to add a given item to the beginning of a given array:
const array = [1, 2, 3];
const item = 4;
array.unshift(item);
Conclusion
And those are a few of the common approaches for adding items to arrays in JavaScript!