JavaScript forEach() Method
Iterate through array elements and perform actions. Useful for side effects and executing code for each element.
What is forEach()?
The forEach() method executes a provided function once for each array element. It doesn't return anything and is used for performing actions on each element (side effects).
Basic forEach() Example
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(num => {
console.log(num * 2);
});
// Logs: 2, 4, 6, 8, 10This example demonstrates how the <code>forEach()</code> method loops through an array and executes a function for every element.
Syntax
forEach() Syntax
array.forEach((element, index, array) => {
// Code to execute for each element
});The <code>forEach()</code> method accepts a callback function that runs for each element in the array. It can receive the element, index, and original array as parameters.
Practical Examples
Log Each Element
Loop Through Array Elements
const fruits = ['apple', 'banana', 'orange'];
fruits.forEach(fruit => {
console.log(fruit);
});
// Logs: apple, banana, orangeThis example shows how <code>forEach()</code> iterates through an array and logs each element to the console. </p>
Update DOM Elements
Update DOM with forEach()
const items = ['Item 1', 'Item 2', 'Item 3'];
items.forEach(item => {
const li = document.createElement('li');
li.textContent = item;
document.getElementById('list').appendChild(li);
});The <code>forEach()</code> method is commonly used to create or update DOM elements by looping through data arrays.
Using Index Parameter
Access Element Index
const colors = ['red', 'green', 'blue'];
colors.forEach((color, index) => {
console.log(`${index + 1}. ${color}`);
});
// Logs: 1. red, 2. green, 3. blueThe callback function in <code>forEach()</code> provides an index parameter that allows you to track the position of each element.
Accumulate Values
Calculate Sum with forEach()
let sum = 0;
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(num => {
sum += num;
});
console.log(sum); // 15
// Better: use reduce() for this!This example shows how <code>forEach()</code> can accumulate values such as calculating the sum of numbers in an array.
Iterate Objects in Array
Iterate Objects in an Array
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 }
];
users.forEach(user => {
console.log(`${user.name} is ${user.age} years old`);
});You can use <code>forEach()</code> to loop through arrays of objects and access their properties easily.
forEach() vs Other Loop Methods
| Method | Returns | Use Case |
|---|---|---|
| forEach() | undefined | Side effects, logging |
| map() | New array | Transform data |
| for loop | N/A | Complex logic, break/continue |
Common Mistakes
❌ Expecting forEach() to Return a Value
forEach() Does Not Return a Value
const numbers = [1, 2, 3];
const result = numbers.forEach(n => n * 2);
console.log(result); // undefined
// Use map() if you need results:
const result = numbers.map(n => n * 2); // [2, 4, 6]The <code>forEach()</code> method always returns <code>undefined</code>. If you need to transform data and return a new array, use <code>map()</code>.
❌ Using forEach() When You Need break/continue
forEach() Does Not Support break or continue
// forEach doesn't support break
numbers.forEach(n => {
if (n > 3) break; // SyntaxError!
});
// Use a for loop instead:
for (const n of numbers) {
if (n > 3) break;
console.log(n);
}Unlike traditional loops, <code>forEach()</code> cannot use <code>break</code> or <code>continue</code>. Use a <code>for</code> loop or <code>for...of</code> when control flow is required.
❌ Modifying Array While Iterating
Avoid Modifying Arrays During Iteration
const arr = [1, 2, 3, 4];
arr.forEach(n => {
if (n > 2) arr.push(n * 2); // Dangerous!
});
// Results in an infinite or unexpected loopChanging the array while iterating with <code>forEach()</code> can lead to unexpected behavior or infinite loops.
FAQs
Can I break out of forEach()?
No, forEach() doesn't support break or continue. Use a for loop if you need to control iteration.
When should I use forEach() vs for loop?
Use forEach() for simple iterations. Use for loops when you need control flow statements (break, continue).
Can I skip elements in forEach()?
Skipping Elements in forEach()
// You can't use continue, but you can use return
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(n => {
if (n < 3) return; // Skips to next iteration
console.log(n);
});
// Logs: 3, 4, 5Although <code>forEach()</code> does not support <code>continue</code>, you can use <code>return</code> inside the callback to skip the current iteration.