How to add an item to an array in JavaScript
Adding items to arrays is one of the most fundamental operations in JavaScript development, essential for building dynamic user interfaces and managing data collections.
As the creator of CoreUI, a widely used open-source UI library, I’ve implemented array manipulation countless times in components that handle dynamic lists, navigation menus, and data tables.
From my expertise, the most efficient and widely supported method is using the push()
method to add items to the end of an array.
This approach is performant, intuitive, and works consistently across all JavaScript environments.
Use the push()
method to add one or more items to the end of an array.
const fruits = ['apple', 'banana']
fruits.push('orange')
// Result: ['apple', 'banana', 'orange']
The push()
method modifies the original array by adding the specified element to the end and returns the new length of the array. In this example, fruits.push('orange')
adds ‘orange’ to the end of the fruits array, changing it from ['apple', 'banana']
to ['apple', 'banana', 'orange']
. You can also add multiple items at once by passing additional arguments: fruits.push('grape', 'kiwi')
.
Best Practice Note:
This is the same approach we use in CoreUI components to dynamically build navigation items and manage component state.
For adding items to the beginning of an array, use unshift()
, and for inserting at specific positions, use splice()
. The push()
method remains the most efficient choice for appending items.