forEach Loop
Imagine a teacher distributing exam results in class. ๐
She picks up the pile of answer sheets and, for each sheet, does the same thing: calls the student's name and hands it over. She doesn't count or skip. She just says: "For each sheet in this pile, do this."
JavaScript arrays have a built-in method that works exactly like this. It is called forEach().
What Is forEach?
forEach() is an array method that runs a function once for every item in the array, from the first item to the last.
Unlike for, while, or for...of, which are loop statements, forEach() is a method. You call it on an array using a dot:
array.forEach(...)
And instead of writing code inside { } directly, you give forEach() a function. This function is called a callback function. JavaScript "calls it back" for each item.
Callback function = a function that you give to another function, so it can run it later.
Think of it like giving instructions to a helper: "Here is a list of tasks, and here is what to do with each one." The helper (forEach) goes through the list, and your instructions (the callback) run for every item.
Syntax
array.forEach(function (item, index, array) {
// code to run for each item
});
The callback function can receive three values:
| Parameter | Meaning | Required? |
|---|---|---|
item | The current item | โ Usually used |
index | The position of the current item (starts from 0) | Optional |
array | The whole array itself | Optional (rarely used) |
You can use any names for these parameters. Only the order matters: item first, then index, then array.
Your First forEach
How It Works, Step by Step
| Round | fruit | Action |
|---|---|---|
| 1 | "Mango" | The callback runs โ prints Mango |
| 2 | "Banana" | The callback runs โ prints Banana |
| 3 | "Apple" | The callback runs โ prints Apple |
| โ | No more items | forEach ends |
No counter, no condition, no .length. forEach() handles everything for you!
Shorter Way: Arrow Functions
Most developers write the callback as an arrow function =>, which is shorter and cleaner.
All three give the same output. We will learn arrow functions in detail in the Functions lesson. For now, just read (fruit) => { ... } as: "take fruit, and do this."
Using the Index
The second parameter gives you the position of each item.
Remember, the index starts from 0, so we add 1 to show ranks starting from 1.
Compare: In
for...of, you need.entries()to get the index. InforEach(), you get it for free. ๐
Using the Third Parameter (array)
The third parameter gives you the whole array. It is useful when you need to look at other items, like the next or previous one.
Real-Life Examples
Example 1: Calculating a shopping bill ๐
Example 2: Printing a bill with item numbers ๐งพ
Example 3: Checking pass or fail โ โ
Example 4: Working with an array of objects ๐
This is very common in real projects, for example when showing orders from a food delivery app.
Example 5: Using a separate named function
You can also write the function separately and pass its name to forEach().
Note: Write forEach(sendWish), not forEach(sendWish()). Adding () would run the function immediately, instead of giving it to forEach.
Changing Array Items with forEach
With primitive values: use the index
Changing the item variable does not change the array, because it is only a copy.
โ Fix: Use the index to update the original array:
With objects: you can change their properties directly
Tip: If you want to create a new array with changed values,
map()is a better choice. You will learn it in the Array Methods lesson.
โ ๏ธ Important Things to Know About forEach
1. You cannot use break or continue
forEach() always goes through every item. There is no way to stop it early using break or continue.
What about return? Inside forEach(), return only skips the current item, like continue. It does not stop the loop.
โ
Need to stop early? Use for...of instead:
2. forEach always returns undefined
forEach() does not give back any value. It just runs the function for each item.
If you want a new array as the result, use map() instead:
3. It works only on arrays (and a few array-like lists)
forEach() is an array method, so it doesn't work directly on plain objects or strings.
let student = { name: "Ravi", age: 20 };
student.forEach(...); // โ TypeError: student.forEach is not a function
"Hello".forEach(...); // โ TypeError
โ Fix for objects: Convert them to an array first:
โ Fix for strings: Split the string into an array of characters:
Map and Set also have their own forEach() method, which you will see in later lessons.
4. Empty slots are skipped
If an array has empty slots, forEach() skips them silently.
5. It doesn't wait for async tasks
forEach() does not wait for tasks like fetching data from the internet to finish. If you need to wait, use for...of with await. You will learn this in the Async JavaScript lesson.
forEach vs for...of vs for Loop
The same task, written three ways:
| Point | for | for...of | forEach() |
|---|---|---|---|
| Type | Loop statement | Loop statement | Array method |
| Gives the index | โ
Manually (i) | Only with .entries() | โ Automatically |
break / continue | โ Yes | โ Yes | โ No |
| Works on | Anything with an index | Arrays, strings, Map, Set | Arrays (and Map, Set) |
| Returns a value | โ | โ | Always undefined |
Waits for await | โ Yes | โ Yes | โ No |
| Code style | Longer | Clean | Short and clean |
Simple way to choose:
- Doing something with every array item, with no stopping needed? โ
forEach()โ - Might need to stop early or skip items? โ
for...of - Need full control over the counter or steps? โ normal
for
Common Mistakes to Avoid
| Mistake | Problem | Fix |
|---|---|---|
Using break or continue | โ SyntaxError | Use for...of |
Expecting return to stop the loop | It only skips the current item | Use for...of with break |
Storing the result of forEach() | Always undefined | Use map() to get a new array |
Calling forEach on an object or string | โ TypeError | Use Object.entries() or [...str] |
Writing forEach(myFunc()) | Runs the function immediately | Write forEach(myFunc) |
Changing item to update the array | The original array is not changed | Use arr[index] |
Quick Summary Table
| Task | Code |
|---|---|
| Basic forEach | arr.forEach((item) => { }) |
| With index | arr.forEach((item, i) => { }) |
| With the whole array | arr.forEach((item, i, arr) => { }) |
| Using a named function | arr.forEach(myFunction) |
| Update primitive items | arr.forEach((v, i, a) => a[i] = ...) |
| Loop through an object | Object.entries(obj).forEach(([k, v]) => { }) |
| Skip one item | if (condition) return; |
Key Takeaways
forEach()is an array method that runs a callback function once for every item in the array.- The callback receives the item, the index, and the whole array, in that order.
- It is short and clean, and you get the index automatically.
- You cannot use
breakorcontinue, andreturnonly skips the current item. Usefor...ofwhen you need to stop early. forEach()always returnsundefined. Usemap()when you need a new array.