JavaScript Array forEach()
š JavaScript Array forEach() Cheatsheet
forEach() runs a function for every element in an array, making it a clean way to perform side effects without a traditional loop.
ā Basic syntax ā Side effects ā forEach vs map ā Using index and original array ā Breaking out early
#javascript #arrays #foreach #iteration #loops #webdev #frontend #coding #tips
Basic syntax
forEach() calls a function once for every element in an array.
It does not return a value and does not mutate the array unless you do so inside the callback.
array.forEach((element, index, array) => {
// side effect
});| Parameter | Description |
|---|---|
element | The current element being processed. |
index | The index of the current element. |
array | The original array forEach was called on. |
Side effects
Unlike map(), forEach() is commonly used to perform side effects rather than to transform data.
Use forEach() when you want to perform an action for each element.
const users = ["Ada", "Grace", "Alan"];
users.forEach((user) => {
console.log(`Hello, ${user}`);
});Or update an external variable.
const scores = [10, 20, 30];
let total = 0;
scores.forEach((score) => {
total += score;
});
console.log(total); // 60forEach vs map
| Method | Returns | Best for |
|---|---|---|
forEach() | undefined | Side effects |
map() | A new array | Transforming data |
const numbers = [1, 2, 3];
// ā
side effect
numbers.forEach((n) => console.log(n));
// ā
transformation
const doubled = numbers.map((n) => n * 2);Using index and original array
Access the index while iterating.
const items = ["a", "b", "c"];
items.forEach((item, index) => {
console.log(`${index}: ${item}`);
});
// 0: a
// 1: b
// 2: cUse the original array for context.
const numbers = [2, 4, 6];
numbers.forEach((n, i, arr) => {
console.log(`${n} is ${i === arr.length - 1 ? "last" : "not last"}`);
});Breaking out early
You cannot break or continue inside forEach(). Use a for...of loop instead.
const numbers = [1, 2, 3, 4, 5];
for (const n of numbers) {
if (n === 3) break;
console.log(n);
}
// 1
// 2Full-Stack AI Developer Roadmap
From HTML & CSS to working with AI models, all in one structured roadmap.