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.
| Argument | Description |
| callbackFn | The function to run for each element. It takes three arguments. |
| 1. element | The value of the current element being processed. |
| 2. index | The index of the current element (starts from 0). |
| 3. array | The 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
insertAdjacentHTMLto add items as strings. If you need to add event listeners or want better security against XSS, you should usedocument.createElementandappendChildinstead. - Omitting Arguments: You can skip the
indexandarrayarguments if you do not need them. In the inventory example, we only used theitemargument.
Important Notes
Cannot Stop the Loop
Once
forEachstarts, it will not stop until it reaches the last element. You cannot usebreakto exit the loop orcontinueto skip an item like you would in a standardforloop. Usingreturninside 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 afor...ofloop.
Asynchronous Behavior
Even if you add
asyncto the callback function,forEachdoes not wait for asynchronous tasks to finish. It will not work withawaitas you might expect. To run asynchronous tasks in a specific order, use afor...ofloop orPromise.allwith themapmethod.
No Return Value
If you want to create a new array by transforming data, use
mapinstead offorEach. The return value offorEachis alwaysundefined.
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.
