JavaScript AcademyProfessional Engineering
Level 2 · Core DevelopmentModule 7: Functional Array ProcessingLesson 31 of 150About 35 minutes

Lesson 31: forEach and iteration

01Opening question

Instead of writing a loop, can you hand an array a function and say "do this for every item"?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

forEach calls your function once per element, passing the element and its index.

const names = ["Ada", "Grace", "Linus"];
names.forEach((name, i) => {
  console.log(i + 1, name);
});

03Objective and prerequisites

Learning objective: Use forEach with its element, index and array parameters, write callbacks inline or by name, and know when forEach is the wrong tool.

You need: Lesson 24: Arrow functions, Lesson 29: Iterating over collections

Skills practised: Functional array processing, Callbacks.

04Explanation

list.forEach(callback) calls the callback once for every element, in order. The callback receives the element, its index and the whole array.

You can pass an arrow function inline, list.forEach((x) => console.log(x)), or a named function, list.forEach(printItem). Do not add brackets when passing a named function: printItem() would call it immediately.

forEach always returns undefined. It is for side effects such as printing, updating a total outside the callback, or changing the page.

You cannot stop forEach early with break. If you need to stop, use for...of, or methods such as find and some.

05Definitions

forEach
Calls a function once for each element of an array.
Callback
A function you pass to another function, which calls it for you.
Side effect
An effect outside a function, such as printing or changing a variable.
Inline function
A function written directly where it is passed as an argument.
Higher-order function
A function that takes or returns another function.

Open the full glossary

06Visual learning object

Callback visualizer. See each call of the callback with its element, index and result, for forEach, map, filter and reduce.

Loading the interactive object…

Open the full Map transformation visualizer page with its guided experiment.

07Examples

ex-031-01Doing something for each element Browser-executable JavaScript

The callback runs once per element.

const items = ["Tea", "Cake"];
items.forEach((item) => console.log("Serving", item));
const result = items.forEach((item) => item);
console.log(result);
Sample input
None
Expected output
Serving Tea Serving Cake undefined
Common mistake
Expecting forEach to return a new array.
Try this
Print each item in capitals.
Source
examples/ex-031-01-print-each.js (repository pending publication)

ex-031-02Passing a named function Browser-executable JavaScript

Pass the function itself, without brackets.

function announce(name, position) {
  console.log(`Now serving #${position + 1}: ${name}`);
}
["Ada", "Grace"].forEach(announce);
Sample input
None
Expected output
Now serving #1: Ada Now serving #2: Grace
Common mistake
Writing forEach(announce()), which calls announce once with no arguments.
Try this
Write a second named callback and use it.
Source
examples/ex-031-02-named-callback.js (repository pending publication)

ex-031-03Updating an outer variable Browser-executable JavaScript

A side effect: the callback adds to a total declared outside.

const prices = [3.5, 4, 2.25];
let total = 0;
prices.forEach((p) => {
  total += p;
});
console.log("Total:", total);
Sample input
None
Expected output
Total: 9.75
Common mistake
Declaring total inside the callback, which resets it each time.
Try this
Also count the prices above 3.
Source
examples/ex-031-03-outer-total.js (repository pending publication)

ex-031-04Element, index and array Browser-executable JavaScript

The third argument is the array itself.

const steps = ["cart", "address", "payment"];
steps.forEach((step, i, all) => {
  const last = i === all.length - 1;
  console.log(step + (last ? " (final)" : " →"));
});
Sample input
None
Expected output
cart → address → payment (final)
Common mistake
Reading steps.length inside a reusable callback instead of the all parameter.
Try this
Show "(first)" on the first step.
Source
examples/ex-031-04-all-three-args.js (repository pending publication)

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Pass the function, do not call it

Fix a callback passed with brackets.

function shout(word) {
  console.log(String(word).toUpperCase());
}
["go", "team"].forEach(shout());

Receipt lines

Use forEach with the index to print and total.

const lines = [
  { name: "Soup", price: 6 },
  { name: "Bread", price: 2.5 }
];
let total = 0;
// TODO: use forEach to print "1. Soup $6.00", "2. Bread $2.50" and add to total
console.log(`Total $${total.toFixed(2)}`);

Tally the votes

Count values into an object with forEach.

const votes = ["tea", "coffee", "tea", "juice", "tea", "coffee"];

09Prediction

Commit to an answer first, then run the real code to compare.

let s = 0;
const r = [1, 2, 3].forEach((n) => { s += n; return n * 2; });
console.log(s, r);

What is printed?

10Debugging investigation

The basket total stays at zero

The basket has three items worth $18, but the total shown is 0.

const basket = [5, 9, 4];
let total = 0;
basket.forEach((price) => {
  let total = 0;
  total += price;
});
console.log("Total:", total);

More cases in the Debugging Detective Laboratory

11Practical scenario

Sending reminders

A booking system sends one reminder per appointment. forEach fits: nothing is returned, each appointment just triggers an action.

const appts = [{ who: "Ada", at: "9:00" }, { who: "Linus", at: "10:30" }];
appts.forEach((a) => console.log(`Reminder to ${a.who}: ${a.at}`));

12Knowledge check

1. What is printed?

console.log([1, 2].forEach((n) => n * 2));
  • undefined
  • [2, 4]
  • 2 4
  • An error

2. What arguments does forEach pass to the callback?

  • Only the element
  • Element, index, array
  • Index only
  • Nothing

3. Why does this throw a TypeError?

function show(x) { console.log(x); }
[1, 2].forEach(show());
  • log is wrong
  • show() is called instead of passed
  • forEach needs an index
  • The array is empty

4. How can you stop a forEach loop early?

  • break
  • return
  • You cannot; use for...of or find/some
  • continue

5. What is printed?

let count = 0;
[5, 6, 7].forEach(() => count++);
console.log(count);
  • 1
  • 3
  • 0
  • 6

6. You need a new array of doubled prices. Which is best?

  • forEach pushing into a new array
  • map
  • for...in
  • sort

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Pass the function, do not call it: Prints GO and TEAM; No error
  • Receipt lines: Prints the receipt; Uses forEach
  • Tally the votes: Prints the tally; tally is correct
  • ex-031-01: output matches the documented expected output
  • ex-031-02: output matches the documented expected output
  • ex-031-03: output matches the documented expected output
  • ex-031-04: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-02-core-development/module-07-functional-array-processing/lesson-031-foreach-and-iteration/. Every example on this page is generated from those files.

The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.

15Summary and next steps

  • forEach calls a function for every element.
  • The callback receives element, index and array.
  • forEach returns undefined: use it for side effects.
  • It cannot be stopped early.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation forEach and callbacks
Context: I am learning forEach and callbacks in JavaScript.
Task: Explain callbacks and forEach with a reminder-sending example, including what forEach returns.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction forEach and callbacks drill
Context: I have practised forEach and callbacks.
Task: Give me six forEach snippets and ask what each prints.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging forEach and callbacks bug
Context: My forEach throws TypeError: undefined is not a function.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation forEach and callbacks practice
Context: I finished the forEach and callbacks exercises.
Task: Create three forEach exercises that print and total data.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review forEach and callbacks review
Context: Here is my code that uses forEach and callbacks.
Task: Review my forEach calls and tell me which would be clearer as map, filter or for...of.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.