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:

ParameterMeaningRequired?
itemThe current itemโœ… Usually used
indexThe position of the current item (starts from 0)Optional
arrayThe whole array itselfOptional (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

RoundfruitAction
1"Mango"The callback runs โ†’ prints Mango
2"Banana"The callback runs โ†’ prints Banana
3"Apple"The callback runs โ†’ prints Apple
โ€”No more itemsforEach 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. In forEach(), 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:

Pointforfor...offorEach()
TypeLoop statementLoop statementArray method
Gives the indexโœ… Manually (i)Only with .entries()โœ… Automatically
break / continueโœ… Yesโœ… YesโŒ No
Works onAnything with an indexArrays, strings, Map, SetArrays (and Map, Set)
Returns a valueโ€”โ€”Always undefined
Waits for awaitโœ… Yesโœ… YesโŒ No
Code styleLongerCleanShort 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

MistakeProblemFix
Using break or continueโŒ SyntaxErrorUse for...of
Expecting return to stop the loopIt only skips the current itemUse for...of with break
Storing the result of forEach()Always undefinedUse map() to get a new array
Calling forEach on an object or stringโŒ TypeErrorUse Object.entries() or [...str]
Writing forEach(myFunc())Runs the function immediatelyWrite forEach(myFunc)
Changing item to update the arrayThe original array is not changedUse arr[index]

Quick Summary Table

TaskCode
Basic forEacharr.forEach((item) => { })
With indexarr.forEach((item, i) => { })
With the whole arrayarr.forEach((item, i, arr) => { })
Using a named functionarr.forEach(myFunction)
Update primitive itemsarr.forEach((v, i, a) => a[i] = ...)
Loop through an objectObject.entries(obj).forEach(([k, v]) => { })
Skip one itemif (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 break or continue, and return only skips the current item. Use for...of when you need to stop early.
  • forEach() always returns undefined. Use map() when you need a new array.