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.
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.
forEach skips holes in sparse arrays and reads length once at the start; elements appended during iteration are not visited.
async callbacks are not awaited: list.forEach(async (x) => await save(x)) starts all saves and continues immediately. Use for...of with await, or Promise.all with map.
Prefer map, filter and reduce when the goal is a new value. forEach with an outer accumulator works, but expresses intent less clearly and invites accidental mutation.
The optional second argument thisArg sets this inside a regular-function callback; arrow callbacks ignore it.
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.
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
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.
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 explanationforEach 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 predictionforEach 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.
DebuggingforEach 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 generationforEach 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 reviewforEach 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.