Add an Item to the End of an Array in JavaScript
Arrays are dynamic in JavaScript, which means you can add or remove items on the fly. One of the most common tasks you'll encounter is appending a new item to the end of an array — like adding a new task to a list, inserting a product to a cart, or logging an event in history.
In this tutorial, we will explore several ways to add elements to the end of an array in JavaScript, with examples and output.
Method 1: Using push()
Method
The push()
method is the most common and straightforward way to append a new item to the end of an array. It modifies the original array and returns the new length of the array.
const fruits = ["apple", "banana"];
const newLength = fruits.push("cherry");
console.log("Updated array:", fruits);
console.log("New length:", newLength);
Updated array: ["apple", "banana", "cherry"]
New length: 3
Method 2: Using Array Length Property
If you want to manually assign a new item to the end of an array, you can use the array's length
property as the next available index. This method gives you more control but is less readable than push()
.
const fruits = ["apple", "banana"];
fruits[fruits.length] = "grape";
console.log("Final array:", fruits);
Final array: ["apple", "banana", "grape"]
Method 3: Using Spread Operator (Non-Mutating)
If you prefer a functional approach that doesn’t modify the original array, the spread operator [...array, newItem]
can be used to create a new array with the additional item. This is especially useful in frameworks like React, where immutability is preferred.
const fruits = ["apple", "banana"];
const updatedFruits = [...fruits, "peach"];
console.log("Original:", fruits);
console.log("Updated:", updatedFruits);
Original: ["apple", "banana"]
Updated: ["apple", "banana", "peach"]
When Should You Use Each Method?
push()
: Use this when you want to update the original array directly. It’s fast, readable, and widely supported.length
assignment: Useful when you want to control the position manually or work with sparse arrays.- Spread operator: Ideal when you need immutability and want to work in a declarative, functional programming style.
Comments
Loading comments...