Side Effects
forEach runs a callback for every element.
It is best when you need side effects like logging or updating external state.
JavaScript Tutorial
forEach runs a callback for each element in the array.
It is best for side effects, not for building new arrays.
Some tasks are about doing something for each item, like logging or updating totals.
forEach expresses that intent clearly.
array.forEach((value, index, array) => { ... })const nums = [1, 2, 3];
nums.forEach((n) => console.log(n));Run a callback for each item.
const items = ["a", "b"];
items.forEach((item, i) => console.log(i, item));Access index and value.
forEach runs a callback for every element.
It is best when you need side effects like logging or updating external state.
forEach always returns undefined.
If you need a new array, use map instead.
You cannot break out of forEach early.
Use a for...of loop when you need break or continue.
const nums = [1, 2, 3];
let total = 0;
nums.forEach((n) => {
total += n;
});
console.log(total);Use forEach for side effects.
const nums = [1, 2, 3];
nums.forEach((n) => {
if (n === 2) return;
console.log(n);
});return only skips the current callback.
Without
const out = [];
for (const n of nums) {
out.push(n * 2);
}With
const out = nums.map((n) => n * 2);Use map or filter to return new arrays.
Use for...of if you need break or continue.
forEach always returns undefined.
No, it returns undefined.
No, use a loop instead.
When you need side effects, not transformations.
Practice: Log each item with its index using forEach.
const items = ["x", "y", "z"];
// TODO: log index and value
One Possible Solution
const items = ["x", "y", "z"];
items.forEach((item, i) => console.log(i, item));No, it returns undefined.
No, use a loop if you need early exit.
For side effects like logging or updating external state.
Try changing the array items and see the output.