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" });
console.log(users);
// [{ name: "Ava" }, { name: "Leo" }, { name: "Mia" }]
Example 4: Append without changing the original array
const original = [1, 2, 3];
const updated = [...original, 4];
console.log(original); // [1, 2, 3]
console.log(updated); // [1, 2, 3, 4]
This is useful when you want to preserve the original array.
Example 5: Append multiple items
const items = [1, 2];
items.push(3, 4, 5);
console.log(items); // [1, 2, 3, 4, 5]
push() can add more than one item at once.
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);- Prints the updated array:
["red", "blue", "green"]
console.log(lengthAfterPush);- Prints:
3
A key detail is that push() returns the new length, not the array itself.
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 (const row of rows) {
if (row.isValid) {
validRows.push(row);
}
}
This pattern is common when filtering or collecting matching records.
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.push("Email must contain @");
}
if (password.length < 8) {
errors.push("Password must be at least 8 characters");
}
Appending is often used to gather validation messages.
5. Combining with higher-level array methods
Developers often use map(), filter(), and reduce() instead of manually appending in loops when the intent is clearer. But push() remains very common when building arrays step by step.
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] = 4;
Prefer:
arr.push(4);
3. Mutating an array when immutability is required
Broken in some state-management situations:
const updated = original;
updated.push(4);
This changes original too, because both variables point to the same array.
Safer version:
const updated = [...original, 4];
4. Adding an array as a single item by mistake
const arr = [1, 2];
arr.push([3, 4]);
console.log(arr); // [1, 2, [3, 4]]
If you wanted separate items instead, use:
arr.push(3, 4);
or
const newArr = [...arr, 3, 4];
5. Confusing push() with concat()
const arr = [1, 2];
const result = arr.concat(3);
console.log(arr); // [1, 2]
console.log(result); // [1, 2, 3]
concat() creates a new array. push() changes the original one.
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
const a = [1, 2];
a.push(3);
// a is now [1, 2, 3]
const a = [1, 2];
const b = [...a, 3];
// a is still [1, 2]
// b is [1, 2, 3]
push() vs concat()
- Use
push()when you want to modify the current array. - Use
concat()when you want a new array.
push() vs unshift()
push()adds to the end.unshift()adds to the beginning.
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(). - Want to keep the old array unchanged? Use
[...array, value]orconcat(). - Want to add to the front instead of the end? Use
unshift().
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()?
push() changes the existing array. concat() returns a new one.
Can I append arrays with push()?
Yes, but an array will be added as a single item unless you spread it:
arr.push(otherArray); // adds as one item
arr.push(...otherArray); // adds each element
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
Abort Ajax Requests with jQuery jqXHR.abort()
Learn how to cancel an in-progress jQuery Ajax request with jqXHR.abort(), handle abort status safely, and avoid stale UI updates.
Access the Correct this Inside a JavaScript Callback
Learn why JavaScript this changes in callbacks and how to preserve an object context using bind, arrow functions, and event handler patterns.
Add Key-Value Pairs to JavaScript Objects
Learn how to add key-value pairs to JavaScript objects with dot and bracket notation, dynamic keys, examples, and common mistakes.