Table of Contents
What forEach() Does
Runs a function on every item: you hand it a function, and it calls that function once for each element, from the first to the last.
Doesn't create a new array: it just performs an action. Nothing gets collected or returned.
Leaves the original array alone: unless you change items yourself inside the function, the array stays as it was.
let fruits = ["apple", "banana", "mango"];
fruits.forEach(fruit => {
console.log(fruit);
});
// apple
// banana
// mango
Syntax and Parameters
array.forEach(function (item, index, array) {
// your code here
});
item: the current element being processed.
index: the position of that element, starting from 0.
array: the full array you're looping through. You'll rarely need this one.
Only the first one is required: most of the time you'll just write item, and skip the rest.
let names = ["Vi", "Sam", "Alex"];
names.forEach((name, index) => {
console.log(`${index + 1}. ${name}`);
});
// 1. Vi
// 2. Sam
// 3. Alex
Practical Examples
Printing items from a list of objects:
let users = [
{ name: "Vi", age: 22 },
{ name: "Sam", age: 30 }
];
users.forEach(user => {
console.log(`${user.name} is ${user.age} years old`);
});
Updating a value outside the array:
let prices = [100, 250, 400];
let total = 0;
prices.forEach(price => {
total += price;
});
console.log(total); // 750
Changing the original objects inside the array:
let tasks = [
{ title: "Study", done: false },
{ title: "Gym", done: false }
];
tasks.forEach(task => {
task.done = true;
});
console.log(tasks);
// both tasks now have done: true
Things to Remember
It always returns undefined: even if you write a return inside, you won't get anything back from forEach() itself.let result = [1, 2, 3].forEach(n => n * 2); console.log(result); // undefined
You can't stop it early: break and continue don't work inside it. If you need to stop partway, use a for loop or for...of instead.
It skips empty slots: in arrays with missing items, those gaps are ignored.
let arr = [1, , 3]; arr.forEach(n => console.log(n)); // 1 // 3It doesn't wait for async code: if you use await inside forEach(), it won't pause the loop the way you'd expect. Use for...of for that.
Common Mistakes
Using forEach() when you need a new array: if you want the transformed results, use map() instead.
Expecting break to work: it won't. Pick a for loop or some() when you might need to stop early.
Using await inside it: the loop won't wait, so things can run out of order.
Conclusion
Frequently Asked Questions (FAQs)
2.What's the difference between forEach() and map()?Not by itself. It only changes the array if your function modifies the items directly.
3.Can I use break inside forEach()?forEach() just runs an action and returns nothing. map() collects the results into a new array.
No. If you need to stop early, use a regular for loop, for...of, or a method like some().
0 Comments