JavaScript push(): How to Add Items to an Array (Examples + Best Practices)

目次

1. Introduction | Make Array Operations Easy in JavaScript!

JavaScript is an essential programming language for building dynamic and interactive web applications. Among its core fundamentals, working with arrays is one of the most frequently used operations.

In this article, we’ll take a detailed look at one of the most important JavaScript array methods: the push() method. With push(), you can easily add elements to an array, opening the door to many practical use cases.

For example, it’s useful in situations like these:

  • Adding products to a shopping cart.
  • Adding new tasks to a ToDo list.
  • Building data dynamically as your app runs.

To keep things beginner-friendly, this guide explains everything step by step—from the basics to practical real-world examples. We’ll also cover common pitfalls and how push() differs from other array methods, so you can apply it effectively in real work.

By the end, you’ll be able to master JavaScript’s push() method and write code more efficiently. Let’s get started with the basics in the next section!

2. push() Basics | How to Add Elements to an Array

To understand array operations in JavaScript, the push() method is a foundational yet powerful tool. In this section, we’ll explain what push() does and how to use it in practice.

What is the push() method?

The push() method is used to add elements to a JavaScript array. With this method, you can add new elements to the end of an array and get the new array length—all in a simple way.

Basic syntax

Here is the basic syntax of push():

arrayName.push(element1, element2, ...);

Example 1: Add a single element

Let’s start with the most basic example—adding one element to an array:

let fruits = ["apple", "banana"];
fruits.push("orange");
console.log(fruits); // ["apple", "banana", "orange"]

In this code, push("orange") adds “orange” to the end of the array.

Example 2: Add multiple elements

push() can also add multiple elements at once:

let numbers = [1, 2];
numbers.push(3, 4, 5);
console.log(numbers); // [1, 2, 3, 4, 5]

In this example, the three elements 3, 4, 5 are added to the end of the array. This is convenient when you want to append multiple values in one operation.

About the return value

push() returns the new length of the array. This makes it easy to immediately know how many elements the array contains.

let colors = ["red", "blue"];
let length = colors.push("green");
console.log(colors); // ["red", "blue", "green"]
console.log(length); // 3

Here, you can confirm that the return value is the new array length (3).

Key takeaways for push()

  • It is a method that adds elements to the end of an array.
  • You can add a single element or multiple elements at once.
  • It returns the new array length as its return value.

3. Practical Examples | Real-World Ways to Use JavaScript push()

In the previous section, you learned the basic usage of push(). In this section, we’ll walk through practical real-world examples to help you use push() more effectively.

3-1. Add elements using spread syntax

In JavaScript, you can use spread syntax (…) to add all elements from another array at once.

Example 1: Add elements from another array

let colors = ["red", "blue"];
let newColors = ["green", "yellow"];
colors.push(...newColors);
console.log(colors); // ["red", "blue", "green", "yellow"]

In this code, spread syntax expands the elements of newColors and appends them to colors. This approach is useful when you want to combine arrays efficiently.

3-2. Add elements to a multidimensional array

push() also works with multidimensional arrays, allowing you to add an array inside another array.

Example 2: Add to a multidimensional array

let matrix = [[1, 2], [3, 4]];
matrix.push([5, 6]);
console.log(matrix); // [[1, 2], [3, 4], [5, 6]]

Here, the new array [5, 6] is added to the end of the existing multidimensional array. This is helpful for managing more complex, layered data structures.

3-3. Manage dynamic data

push() is a great fit for dynamic data management. Below is an example of a simple shopping cart feature.

Example 3: Add items to a shopping cart

let cart = [];

function addItem(item) {
  cart.push(item);
  console.log(`Added ${item} to the cart. Current cart:`, cart);
}

addItem("T-shirt"); // Added T-shirt to the cart. Current cart: ["T-shirt"]
addItem("Jeans");   // Added Jeans to the cart. Current cart: ["T-shirt", "Jeans"]

This example uses a function to add products to a cart array. Because data can be added dynamically during program execution, this pattern is widely used in e-commerce sites and task management apps.

3-4. Add elements conditionally

By combining push() with conditional logic, you can build more flexible behavior.

Example 4: Check for duplicates

let items = ["apple", "banana"];

function addItem(item) {
  if (!items.includes(item)) {
    items.push(item);
    console.log(`Added ${item}:`, items);
  } else {
    console.log(`${item} already exists.`);
  }
}

addItem("orange"); // Added orange: ["apple", "banana", "orange"]
addItem("apple");  // apple already exists.

This code prevents duplicates by checking whether the item already exists with includes(). This type of logic is useful for filtering and organizing data.

3-5. Collect data using push()

push() is also useful for real-time data collection and event handling.

Example 5: Record user input

let inputs = [];

document.addEventListener('keydown', (event) => {
  inputs.push(event.key);
  console.log("Input history:", inputs);
});

This example records keyboard input history in an array. It can be applied to interactive applications and form input tracking.

3-6. Combine push() with other methods

When used with other array methods, push() can support more complex processing.

Example 6: Combine map() and push()

let numbers = [1, 2, 3];
let doubled = [];

numbers.map(num => doubled.push(num * 2));
console.log(doubled); // [2, 4, 6]

Here, map() processes each element, and push() collects the results into a new array. This technique can be useful for transformations and filtering workflows.

Summary

In this section, you explored practical examples of push(). Key points include:

  • Adding multiple elements using spread syntax.
  • Adding arrays to multidimensional arrays.
  • Implementing dynamic data management and conditional adds.
  • Processing data by combining push() with other methods.

By using these techniques, you can greatly increase flexibility in JavaScript programming.

In the next section, we’ll explain the return value of push() in more detail. Let’s continue learning how to use it effectively!

4. Return Value Explained | How to Use What push() Returns

In the previous section, you learned practical use cases for push(). In this section, we’ll take a closer look at the return value of push() and show how to use it in real scenarios.

4-1. What does push() return?

push() returns the length of the array after the new elements have been added.

Basic example

let fruits = ["apple", "banana"];
let length = fruits.push("orange");
console.log(fruits); // ["apple", "banana", "orange"]
console.log(length); // 3

In this example, after “orange” is added, the return value is the array length 3.

4-2. When is the return value useful?

The return value of push() is mainly useful in the following scenarios.

Case 1: Dynamically track array length

You can add new data while tracking the number of elements in real time.

let tasks = [];
let length = tasks.push("Task 1");
console.log(`You now have ${length} task(s).`); // You now have 1 task(s).

This is helpful when you want to display changes immediately as data grows.

Case 2: Use it with conditional logic

You can switch behavior based on the number of elements after adding.

let orders = ["item1"];
let count = orders.push("item2");

if (count > 3) {
  console.log("Too many orders. Please split the processing.");
} else {
  console.log(`Current order count: ${count}`);
}

This example shows a warning when the number of orders exceeds a threshold—useful for dynamic data handling in real applications.

Case 3: Use push() together with other operations

The return value of push() can also support other workflows.

Example: Merge arrays while confirming size

let numbers = [1, 2, 3];
let additionalNumbers = [4, 5];

additionalNumbers.forEach(num => numbers.push(num));
console.log(numbers); // [1, 2, 3, 4, 5]
console.log(numbers.length); // 5

This code appends elements in a loop while keeping the length under control.

4-3. Comparing push() return value with other array methods

Besides push(), several array methods return useful values. Let’s compare them in the table below.

MethodOperationReturn value
push()Add element(s) to the end of an arrayNew array length (number)
pop()Remove the last elementRemoved element
shift()Remove the first elementRemoved element
unshift()Add element(s) to the beginningNew array length (number)
concat()Merge arrays (non-mutating)New array

As you can see, push() and unshift() return the new array length, which makes them useful for size tracking.

4-4. Important notes when using the return value

Note 1: The return value is NOT the array

push() returns a number (length), not the array itself. If you treat it like an array, you may get errors.

Incorrect example:

let arr = [1, 2, 3];
let result = arr.push(4);
console.log(result[0]); // Error

Correct example:

let arr = [1, 2, 3];
arr.push(4);
console.log(arr[0]); // 1

Note 2: push() is a mutating method

push() modifies the original array directly. If you want to preserve the original, create a copy first.

Example: Add data without mutating the original

let original = [1, 2, 3];
let copy = [...original]; // Create a copy with spread syntax
copy.push(4);

console.log(original); // [1, 2, 3]
console.log(copy);     // [1, 2, 3, 4]

Summary

In this section, you learned how the return value of push() works. Key points include:

  • The return value of push() is the new array length.
  • You can use it for data tracking and conditional branching.
  • Because it mutates the original array, be careful if you need to preserve data.

In the next section, we’ll compare push() with other array methods in more detail and explain how to choose the right one for each situation.

5. Method Comparison Table | push vs pop vs shift vs unshift Explained

JavaScript provides several useful array methods. In particular, pop(), shift(), and unshift() are often used alongside push(). In this section, we’ll compare these methods in detail and explain how to choose the right one depending on the situation.

5-1. Overview of array operation methods

Below is a list of major array methods and what they do.

MethodWhat it doesWhere it adds/removesMutating / Non-mutatingReturn value
push()Add element(s) to the end of an arrayEndMutatingNew array length
pop()Remove 1 element from the end of an arrayEndMutatingRemoved element
shift()Remove 1 element from the beginning of an arrayBeginningMutatingRemoved element
unshift()Add element(s) to the beginning of an arrayBeginningMutatingNew array length
concat()Merge arrays (does not change the original array)Non-mutatingNew array

As shown above, push() and unshift() are used to add elements, while pop() and shift() are used to remove elements. The key difference is where the element is added or removed (beginning vs end), and that affects performance and usage patterns.

5-2. Differences between push() and pop()

push() and pop() both operate on the end of an array.

push(): Add to the end

let fruits = ["apple", "banana"];
fruits.push("orange");
console.log(fruits); // ["apple", "banana", "orange"]
  • Best for: Adding new data continuously.
  • Example use cases: Shopping carts, task lists, building log data.

pop(): Remove from the end

let fruits = ["apple", "banana", "orange"];
let removed = fruits.pop();
console.log(fruits); // ["apple", "banana"]
console.log(removed); // "orange"
  • Best for: Taking items off the end one by one, or implementing a stack (LIFO).
  • Example use cases: Undo features, browser history navigation, stack processing.

5-3. Differences between unshift() and shift()

unshift() and shift() operate on the beginning of an array, which is the opposite side of push()/pop().

unshift(): Add to the beginning

let numbers = [2, 3, 4];
numbers.unshift(1);
console.log(numbers); // [1, 2, 3, 4]
  • Best for: Inserting higher-priority items at the front.
  • Example use cases: Priority tasks, inserting urgent jobs first.

shift(): Remove from the beginning

let numbers = [1, 2, 3, 4];
let first = numbers.shift();
console.log(numbers); // [2, 3, 4]
console.log(first);   // 1
  • Best for: Queue-like processing (FIFO), where the first item is handled first.
  • Example use cases: Ticket systems, request queues, task scheduling.

5-4. Mutating vs non-mutating methods

push(), pop(), shift(), and unshift() are all mutating methods, meaning they modify the original array directly.

In contrast, concat() is a non-mutating method that returns a new array without changing the original.

Example: concat() keeps the original array unchanged

let arr = [1, 2, 3];
let newArr = arr.concat(4);

console.log(arr);     // [1, 2, 3] (original stays the same)
console.log(newArr);  // [1, 2, 3, 4] (a new array is created)
  • If you want to preserve the original data, prefer non-mutating methods.

5-5. Practical example | Manage a list by combining methods

By combining multiple methods, you can manage data structures more flexibly.

let queue = [];

// Add elements
queue.push("Task1");     // Add to the end
queue.unshift("Task0");  // Add to the beginning

console.log(queue); // ["Task0", "Task1"]

// Remove elements
let firstTask = queue.shift(); // Remove from the beginning
console.log(firstTask); // "Task0"

let lastTask = queue.pop(); // Remove from the end
console.log(lastTask); // "Task1"

This example demonstrates dynamic list management using push(), unshift(), shift(), and pop() together.

Summary

In this section, you learned the differences between push() and other array methods:

  • push() and pop(): Operate on the end of an array.
  • unshift() and shift(): Operate on the beginning of an array.
  • concat(): A non-mutating method that does not change the original array.

By using the right method for the right situation, you can manage data more efficiently depending on the structure you need.

In the next section, we’ll cover important precautions and best practices for using push() safely and effectively.

6. Notes and Best Practices | Tips for Using push() Safely

So far, you’ve learned the basics and practical examples of push(). While push() is very convenient, using it incorrectly can cause bugs or unexpected behavior. In this section, we’ll cover important precautions and best practices so you can use push() safely.

6-1. push() is a “mutating method”

push() is a mutating method, meaning it modifies the original array directly. If you don’t understand this behavior, it can lead to data inconsistencies and unexpected results.

Example: The original array gets changed

let original = [1, 2, 3];
let modified = original; // Reference copy
modified.push(4);

console.log(original); // [1, 2, 3, 4] - original is also changed
console.log(modified); // [1, 2, 3, 4]

Important note:
Because modified references the same array as original, calling push() changes both.

Solution: Create a copy before modifying the array to protect the original data.

let original = [1, 2, 3];
let copy = [...original]; // Create a copy with spread syntax
copy.push(4);

console.log(original); // [1, 2, 3] - original stays unchanged
console.log(copy);     // [1, 2, 3, 4] - only the copy changes

6-2. push() only works on arrays

push() is an array-specific method. Using it on other data types (like objects) will cause errors or unexpected behavior.

Incorrect example:

let obj = {};
obj.push("value"); // TypeError: obj.push is not a function

Correct example:

If you want to add data to an object, assign a key and value directly:

let obj = { key: "value" };
obj.newKey = "newValue";
console.log(obj); // { key: "value", newKey: "newValue" }

Key point:

  • Use push() for arrays, and use direct key assignment for objects.

6-3. Performance considerations

push() can become expensive if you add a very large number of elements one by one. If you’re handling large-scale data, keep the following in mind.

Add in bulk instead of one by one

Inefficient example:

let numbers = [];
for (let i = 0; i < 10000; i++) {
  numbers.push(i);
}

More efficient example:

let numbers = [];
numbers.push(...Array.from({ length: 10000 }, (_, i) => i));

Using spread syntax or bulk operations can improve efficiency.

6-4. Use conditional adds

When using push(), it’s important to confirm conditions so unnecessary data isn’t added.

Example: Prevent duplicates

let items = ["apple", "banana"];

function addItem(item) {
  if (!items.includes(item)) {
    items.push(item);
    console.log(`Added ${item}:`, items);
  } else {
    console.log(`${item} already exists.`);
  }
}

addItem("orange"); // Added orange: ["apple", "banana", "orange"]
addItem("apple");  // apple already exists.

This example prevents duplicate data from being added.

6-5. Be careful with method chaining

push() returns the new array length, not the array itself. That means it does not support method chaining.

Error example:

let arr = [1, 2];
arr.push(3).push(4); // TypeError: arr.push(...).push is not a function

Solution:

Add multiple elements in one call, or call push() separately:

let arr = [1, 2];
arr.push(3, 4);
console.log(arr); // [1, 2, 3, 4]

6-6. Combine push() with functions safely

When using push() inside a function, validating inputs can prevent bugs before they happen.

Example: Add input validation

let tasks = [];

function addTask(task) {
  if (typeof task === "string" && task.trim() !== "") {
    tasks.push(task);
    console.log(`${task} was added.`);
  } else {
    console.log("Invalid task.");
  }
}

addTask("Task1"); // Task1 was added.
addTask("");      // Invalid task.

Summary

In this section, you learned key precautions and best practices for using push() safely.

Main points:

  1. Because push() mutates arrays, create a copy if you need to preserve the original.
  2. push() is only for arrays—do not use it on other data types.
  3. Consider performance by using bulk operations and conditional logic.
  4. Be careful with method chaining, and add multiple items in one call when possible.

With these tips, you can use push() more safely and efficiently in real projects.

In the next section, we’ll answer common questions in a FAQ format to help you clear up remaining doubts.

7. FAQ | Common Questions About the push() Method

In this section, we’ll cover frequently asked questions about JavaScript’s push() method with clear examples. This is designed to help beginners avoid common confusion and also answer more advanced practical questions.

Q1. What is the difference between push() and concat()?

A:
Both push() and concat() can be used to add elements to an array, but they behave very differently.

push()

  • A mutating method that directly modifies the original array.
  • Return value: The new array length.

Example:

let arr = [1, 2];
arr.push(3);
console.log(arr); // [1, 2, 3]

concat()

  • A non-mutating method that creates and returns a new array.
  • Return value: A new array.

Example:

let arr = [1, 2];
let newArr = arr.concat(3);
console.log(arr);    // [1, 2] - original array is unchanged
console.log(newArr); // [1, 2, 3]

Key point:

  • Use concat() when you want to keep the original array unchanged.
  • Use push() when you want to modify the original array directly.

Q2. Can push() be used with objects?

A:
No. push() is an array-only method and cannot be used on objects.

Incorrect example:

let obj = {};
obj.push("value"); // TypeError: obj.push is not a function

Correct example:

To add values to an object, specify a key and assign a value:

let obj = { key: "value" };
obj.newKey = "newValue";
console.log(obj); // { key: "value", newKey: "newValue" }

Key point:

  • Use push() for arrays, and use key/value assignment for objects.

Q3. How can I avoid duplicates when using push()?

A:
push() does not include a built-in duplicate check, but you can easily prevent duplicates with conditional logic.

Example: Prevent duplicates

let items = ["apple", "banana"];

function addItem(item) {
  if (!items.includes(item)) {
    items.push(item);
    console.log(`Added ${item}:`, items);
  } else {
    console.log(`${item} already exists.`);
  }
}

addItem("orange"); // Added orange: ["apple", "banana", "orange"]
addItem("apple");  // apple already exists.

Key point:

  • Use includes() to check whether an item already exists before adding it.

Q4. What is an efficient way to manage data using push()’s return value?

A:
Because push() returns the new array length, it is useful for tracking the number of elements in real time.

Example: Track task count in real time

let tasks = [];

function addTask(task) {
  let count = tasks.push(task);
  console.log(`Added "${task}". Current task count: ${count}`);
}

addTask("Task 1"); // Added "Task 1". Current task count: 1
addTask("Task 2"); // Added "Task 2". Current task count: 2

Key point:

  • If you need real-time tracking, use the return value of push().

Q5. How can I work with arrays in a non-mutating way?

A:
push() is mutating, but if you want to avoid changing the original array, use spread syntax (or concat()).

Example: Add elements without mutating

let original = [1, 2, 3];
let newArray = [...original, 4];
console.log(original);  // [1, 2, 3] - original is unchanged
console.log(newArray); // [1, 2, 3, 4]

Key point:

  • Use spread syntax or concat() when you need to preserve the original data.

Q6. Can push() add multiple elements at once?

A:
Yes. push() can add multiple elements in a single call.

Example: Add multiple elements

let colors = ["red"];
colors.push("blue", "green", "yellow");
console.log(colors); // ["red", "blue", "green", "yellow"]

Key point:

  • Use comma-separated values to add multiple elements efficiently.

Summary

In this section, we answered common questions about push().

Main points:

  1. push() vs concat(): Choose between mutating and non-mutating behavior.
  2. Data types: push() is for arrays only, not objects.
  3. Prevent duplicates: Add checks with includes().
  4. Use return value: Track the number of elements in real time.
  5. Non-mutating approach: Use spread syntax to preserve the original array.
  6. Add multiple elements: push() supports adding multiple items at once.

In the next section, we’ll wrap up the entire article with a full summary and suggestions for what to learn next.

8. Conclusion | Learn JavaScript Efficiently with push()

In this article, we covered JavaScript’s push() method from the basics to practical use cases. push() plays a central role in array operations and is a powerful tool for managing data and handling dynamic behavior. Let’s review what you learned and how to apply it.

8-1. Key takeaways from this article

  1. Basic usage
  • push() is a method that adds elements to the end of an array, and it can add one or multiple elements at once.
  • The return value is the new array length.
  1. Practical examples
  • You can add multiple elements using spread syntax and also handle multidimensional arrays.
  • We introduced real-world examples like shopping carts and queue management.
  1. Using the return value
  • The return value can be used for tracking element count and conditional branching.
  1. Comparison with other methods
  • You learned how push() differs from pop(), shift(), and unshift(), and how to choose the right one.
  • We also introduced concat() as a non-mutating alternative.
  1. Notes and best practices
  • Because push() is mutating, you should create a copy when you need to preserve original data.
  • You learned how to prevent bugs using duplicate checks and performance optimization.
  1. FAQ
  • We answered common questions and provided practical tips for real-world use.

8-2. Next steps to level up your array skills

push() is a core skill in JavaScript array operations, but combining it with other methods allows more advanced workflows.

Recommended articles to continue learning

  • Array Operations Basics | Complete Guide to JavaScript Array Methods
  • What is concat()? How to Add Data Without Mutating Arrays
  • JavaScript Object Basics | Understanding the Difference Between Arrays and Objects

These topics will help you deepen your understanding of arrays and objects even further.

8-3. Practice tip | Learn faster by writing code

Programming becomes clearer when you actually write code. Try building small projects like these to practice push().

  1. ToDo list app
  • Implement features to add tasks and manage completed tasks.
  1. Shopping cart feature
  • Add items to a cart and calculate total quantity and total price.
  1. Event log system
  • Record user actions and display the history later.

8-4. Final thoughts

JavaScript’s push() method is a simple but powerful tool. It’s a great first step toward mastering array operations and building more advanced programming skills.

Practical tips:

  • Start with the basics, then apply real examples to handle different data operations.
  • Understand how push() differs from other methods and choose the best approach for each situation.
  • Use best practices to prevent bugs and write safe, maintainable code.

By keeping these points in mind, you can continue improving your JavaScript skills.

8-5. More resources to support your learning

Related resources:

One last message

JavaScript’s push() method is extremely simple, yet highly versatile. Use what you learned in this article to write more efficient and practical code.

 

広告