[JavaScript]Mastering the forEach Method for Array Iteration

目次

Overview

When you want to retrieve and process data stored in an array one by one, the forEach method is recommended. It is simpler and easier to read than a traditional for loop. This article explains how to execute a function for each element in an array to perform actions like DOM manipulation or logging. We will also discuss important limitations, such as the fact that you cannot use the break statement.


Specifications

The forEach Method

This method executes a specific function (callback function) for every element in the array.

ArgumentDescription
callbackFnThe function to run for each element. It takes three arguments.
1. elementThe value of the current element being processed.
2. indexThe index of the current element (starts from 0).
3. arrayThe original array that called forEach.
  • Return Value: undefined (It does not create a new array).

Basic Usage

1. Accessing Elements and Indices

Here is a basic example of displaying array contents in the console in order.

const serverNodes = ['Node-A', 'Node-B', 'Node-C'];

// The first argument is the element, the second is the index
serverNodes.forEach((node, index) => {
    console.log(`${index}: ${node}`);
});

/*
Output:
0: Node-A
1: Node-B
2: Node-C
*/

Full Code (Inventory Management System)

In this scenario, we use an array of product data to dynamically create an HTML list for an inventory display.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inventory Manager</title>
    <style>
        .inventory-panel {
            font-family: sans-serif;
            max-width: 500px;
            border: 1px solid #ccc;
            padding: 20px;
            border-radius: 8px;
        }
        .item-row {
            padding: 10px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
        }
        .item-row:last-child {
            border-bottom: none;
        }
        .stock-alert {
            color: red;
            font-weight: bold;
        }
        .stock-ok {
            color: green;
        }
    </style>
</head>
<body>

<div class="inventory-panel">
    <h2>Current Stock Status</h2>
    <div id="stock-list">
        </div>
</div>

<script src="inventory.js"></script>
</body>
</html>

JavaScript

/**
 * Script to display the inventory list
 */

// 1. Define data (Simulating data from an API)
const inventoryData = [
    { id: 101, name: 'Wireless Mouse', price: 3500, stock: 15 },
    { id: 102, name: 'Mechanical Keyboard', price: 12000, stock: 2 },
    { id: 103, name: 'USB-C Hub', price: 4500, stock: 0 },
    { id: 104, name: 'Monitor Arm', price: 8000, stock: 8 }
];

const listContainer = document.getElementById('stock-list');

// 2. Loop through the array and generate DOM elements
// Use forEach to access each product object (item)
inventoryData.forEach((item) => {
    let statusHTML = '';
    
    // Determine status based on stock level
    if (item.stock === 0) {
        statusHTML = '<span class="stock-alert">Out of Stock</span>';
    } else if (item.stock < 5) {
        statusHTML = `<span class="stock-alert">Only ${item.stock} left</span>`;
    } else {
        statusHTML = '<span class="stock-ok">In Stock</span>';
    }

    // Build the HTML string
    const rowHTML = `
        <div class="item-row">
            <span class="item-name">${item.name}</span>
            <span class="item-status">${statusHTML}</span>
        </div>
    `;

    // Add to the container using insertAdjacentHTML for better performance
    listContainer.insertAdjacentHTML('beforeend', rowHTML);
});

Customization Points

  • Changing DOM Methods: In the example above, we use insertAdjacentHTML to add items as strings. If you need to add event listeners or want better security against XSS, you should use document.createElement and appendChild instead.
  • Omitting Arguments: You can skip the index and array arguments if you do not need them. In the inventory example, we only used the item argument.

Important Notes

Cannot Stop the Loop

Once forEach starts, it will not stop until it reaches the last element. You cannot use break to exit the loop or continue to skip an item like you would in a standard for loop. Using return inside the function will only skip the current iteration and move to the next item. If you need to stop the loop early based on a condition, use a for...of loop.

Asynchronous Behavior

Even if you add async to the callback function, forEach does not wait for asynchronous tasks to finish. It will not work with await as you might expect. To run asynchronous tasks in a specific order, use a for...of loop or Promise.all with the map method.

No Return Value

If you want to create a new array by transforming data, use map instead of forEach. The return value of forEach is always undefined.


Advanced Applications

You can combine filter and forEach to create powerful data processing chains. This allows you to narrow down data and then act on it immediately.

const serverLogs = [10, 25, 32, 47, 50, 63];

// 1. Extract only even numbers (filter)
// 2. Output to console (forEach)
serverLogs
    .filter(num => num % 2 === 0)
    .forEach(num => {
        console.log(`Even number detected: ${num}`);
    });

/*
Output:
Even number detected: 10
Even number detected: 32
Even number detected: 50
*/

Summary

The forEach method is the best choice when you want to take a specific action for every item in an array, such as displaying data or updating UI elements. It is easier to read and less prone to errors compared to traditional for loops because you do not have to manage the index manually. However, you must remember that you cannot stop this loop with a break statement and it does not handle asynchronous code well. Choosing the right loop for the job is essential for writing robust JavaScript applications.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次