JavaScript provides several ways to work with arrays, including adding one or more elements. In this article, we’ll cover the most common methods for extending arrays — push() and concat() — along with a few other useful techniques and best practices.
Adding a Single Element to a JavaScript Array
The push() method
The push() method is one of the simplest and most commonly used ways to add elements to the end of an array. This method mutates the original array, which can be convenient when you need to preserve the reference to the same object.
const items = ['item1', 'item2', 'item3'];
items.push('item4');
In the example above, the items array now contains: ['item1', 'item2', 'item3', 'item4'].
The concat() method
An alternative to push() is the concat() method, which creates a new array by appending elements to an existing one. Unlike push(), concat() does not modify the original array, making it preferable in functional programming and scenarios where data immutability is important.
const items = ['item1', 'item2', 'item3'];
const allItems = items.concat('item4');
Now, allItems contains ['item1', 'item2', 'item3', 'item4'], while the original items array remains unchanged.
Adding Multiple Elements
Both push() and concat() can be used to add multiple elements at once. Using push(), you can pass several arguments, and all of them will be added to the end of the array:
const items = ['item1', 'item2', 'item3'];
items.push('item4', 'item5', 'item6');
The concat() method, on the other hand, can combine arrays as well as individual elements:
const items = ['item1', 'item2', 'item3'];
const moreItems = ['item4', 'item5', 'item6'];
const allItems = items.concat(moreItems);
Other Useful Methods and Practices
The unshift() method adds one or more elements to the beginning of an array and modifies the original array:
const items = ['item1', 'item2', 'item3'];
items.unshift('item0');
The spread operator (…) is a modern and elegant way to copy and combine arrays or add elements without mutating existing data:
const items = ['item1', 'item2', 'item3'];
const newItems = ['item0', ...items, 'item4'];
This method is especially useful when creating new arrays that merge existing ones with new values.
Conclusion
JavaScript offers a wide range of tools for efficient array manipulation. The right method depends on your specific use case and whether you want to mutate or preserve the original array. By mastering push(), concat(), unshift(), and the spread operator, developers can easily add elements to arrays while keeping their code clean, functional, and maintainable.