Question
How can I append a value, such as a string, number, or object, to an array in JavaScript?
For example, if I already have an array, how do I add a new item to the end of it?
Short Answer
By the end of this page, you will understand how to add items to the end of a JavaScript array, when to use push(), when to create a new array instead, and how this choice affects real code.
Concept
In JavaScript, an array stores an ordered list of values. Appending means adding a new item to the end of that list.
The most direct way to do this is with the array method push():
const numbers = [1, 2, 3];
numbers.push(4);
console.log(numbers); // [1, 2, 3, 4]
This matters because arrays are used everywhere in programming:
- storing user records
- collecting form inputs
- building lists for APIs
- processing results from databases
- tracking logs, messages, or events
There are two common ways to append an item:
- Mutate the existing array using
push() - Create a new array using spread syntax
const arr = [1, 2, 3];
const newArr = [...arr, 4];
Both are valid, but they are used in different situations. In everyday JavaScript, push() is simple and efficient. In codebases that prefer immutability, such as React state updates, creating a new array is often the better choice.
Mental Model
Think of an array like a train made of connected carriages.
- The array is the whole train.
- Each item is one carriage.
- Appending means attaching a new carriage to the end of the train.
Using push() is like physically attaching the new carriage to the existing train.
Using spread syntax is like building a new train with all the old carriages plus one extra at the end.
Both produce a train with one more carriage, but one changes the original train and the other creates a new one.
Syntax and Examples
The most common syntax is:
array.push(value);
Example 1: Append a string
const fruits = ["apple", "banana"];
fruits.push("orange");
console.log(fruits); // ["apple", "banana", "orange"]
push() adds the item to the end of the existing array.
Example 2: Append a number
const scores = [10, 20, 30];
scores.push(40);
console.log(scores); // [10, 20, 30, 40]
Example 3: Append an object
const users = [{ name: "Ava" }, { name: "Leo" }];
users.push({ name: "Mia" });
.(users);
Step by Step Execution
Consider this example:
const colors = ["red", "blue"];
const lengthAfterPush = colors.push("green");
console.log(colors);
console.log(lengthAfterPush);
Step by step:
-
const colors = ["red", "blue"];- A new array is created with two items.
-
const lengthAfterPush = colors.push("green");- JavaScript adds
"green"to the end ofcolors. - The array becomes
["red", "blue", "green"]. push()returns the new length of the array, which is3.- So
lengthAfterPushbecomes3.
- JavaScript adds
-
console.log(colors);
Real World Use Cases
Appending to arrays is common in real programs.
Collecting user input
const tags = ["javascript", "arrays"];
tags.push("beginner");
Useful when users add tags, comments, or selected options.
Building API request data
const payload = [];
payload.push({ id: 1, action: "create" });
payload.push({ id: 2, action: "update" });
This helps assemble batches of data before sending them to a server.
Logging events
const events = [];
events.push("page_loaded");
events.push("button_clicked");
A script may append events as they happen.
Processing file or database results
const validRows = [];
for ( row rows) {
(row.) {
validRows.(row);
}
}
Real Codebase Usage
In real projects, developers use array appending in a few common ways.
1. Building results inside loops
const completedTasks = [];
for (const task of tasks) {
if (task.done) {
completedTasks.push(task);
}
}
This is a basic collection pattern.
2. Guard clauses before appending
function addUsername(usernames, name) {
if (!name) return usernames;
usernames.push(name);
return usernames;
}
Validation often happens before adding data.
3. Immutable updates in frameworks
const nextTodos = [...todos, newTodo];
This is common in React and other state-driven code, where changing the original array directly may cause bugs.
4. Error-safe data collection
const errors = [];
if (!email.includes("@")) {
errors.();
}
(password. < ) {
errors.();
}
Common Mistakes
1. Expecting push() to return the array
Broken code:
const arr = [1, 2, 3];
arr = arr.push(4);
Problems:
arrwas declared withconst, so reassignment is not allowed.push()returns the new length, not the updated array.
Correct version:
const arr = [1, 2, 3];
arr.push(4);
console.log(arr); // [1, 2, 3, 4]
2. Using array length manually when push() is clearer
This works, but is less readable:
const arr = [1, 2, 3];
arr[arr.length] = ;
Comparisons
| Approach | Changes original array? | Returns | Best for |
|---|---|---|---|
array.push(value) | Yes | New length | Simple direct append |
array[array.length] = value | Yes | Assigned value | Rarely used manually |
[...array, value] | No | New array | Immutable updates |
array.concat(value) | No | New array | Combining arrays or values |
push() vs spread syntax
a = [, ];
a.();
Cheat Sheet
// Add one item to the end
array.push(value);
// Add multiple items to the end
array.push(value1, value2, value3);
// Create a new array with one extra item
const newArray = [...array, value];
// Create a new array using concat
const newArray2 = array.concat(value);
Key rules
push()modifies the original array.push()returns the new length.- Spread syntax does not modify the original array.
concat()also returns a new array.
Edge cases
const arr = [];
arr.push(undefined); // valid
arr.push(null); // valid
arr.push({}); // valid
arr.push([]); // valid
Quick decision guide
- Want to change the same array? Use
push().
FAQ
How do I add an item to the end of an array in JavaScript?
Use push():
arr.push(newItem);
Does push() return the updated array?
No. It returns the new length of the array.
How do I append an object to a JavaScript array?
Use push() the same way:
users.push({ name: "Sam" });
How do I append without changing the original array?
Use spread syntax:
const updated = [...original, newItem];
Can push() add multiple items at once?
Yes.
arr.push(1, 2, 3);
What is the difference between push() and concat()?
Mini Project
Description
Build a small JavaScript program that manages a shopping list. This project demonstrates how to append items to an array, display the updated list, and use both mutable and immutable approaches.
Goal
Create a shopping list that can add new items to the end of an array and show the result after each update.
Requirements
- Start with an array containing at least two shopping items.
- Add a new item to the end using
push(). - Add multiple items in one operation.
- Create a second updated array using spread syntax without changing the first one.
Keep learning
Related questions
Adding Table Rows with jQuery: append(), Limits, and Best Practices
Learn how to add table rows in jQuery using append(), what elements are allowed in tables, and safer ways to build rows dynamically.
Bower vs npm: What’s the Difference in JavaScript Package Management?
Learn the plain difference between Bower and npm, how each manages packages, and why npm replaced Bower in most JavaScript projects.
Can `(a == 1 && a == 2 && a == 3)` Ever Be True in JavaScript?
Learn how JavaScript type coercion, loose equality, and custom object conversion can make `a == 1 && a == 2 && a == 3` true.