.forEach()

The full text of this chapter, to read or revisit. To practise, do the exercises.

β–Ά Do the exercises

Exercise 1 β€” A Built-in Loop

Arrays have a special method for looping over their elements: `forEach`. It takes a callback and calls it once per element.

const team = ["Aquachu", "Pyrochu", "Zap"]; team.forEach((cdm) => { console.log(cdm + " joins the battle!"); });

It's a method of the array, so it's called with a dot. The callback receives each element in turn, exactly like the loop variable of `for...of`.

array.forEach((element) => { // runs once per element });

Exercise 2 β€” forEach vs for...of

Both `for` and `forEach` visit every element. Here is the same task with a `for...of` loop:

const levels = [5, 8, 3]; for (let level of levels) { console.log("Level " + level); }

And now with `forEach`:

const levels = [5, 8, 3]; levels.forEach((level) => console.log("Level " + level));

Same output. `forEach` reads as a sentence: "for each level, do this". It's the preferred style in modern code when you just want to run something on every element.

Exercise 3 β€” Quiz: How Many Lines?

How many lines does this code print?

const moves = ["Spark", "Thunder", "Charge", "Zap Cannon"]; moves.forEach((move) => console.log(move));
Options
β€’ 4
β€’ 1
β€’ 3
β€’ 0

Hint : The callback runs once per element.

Exercise 4 β€” Greet the Team

Print `Hello X!` for every member of the team.

Hint : The method name says what it does, and the parameter must match what the body uses.

Exercise 5 β€” The Index, If You Need It

The callback can take a second parameter: the index of the element. Useful for numbered lists.

const team = ["Aquachu", "Pyrochu", "Zap"]; team.forEach((cdm, index) => { console.log((index + 1) + ". " + cdm); });

You name the parameters yourself, but the order is fixed: element first, index second.

Exercise 6 β€” Quiz: Second Parameter

What does this code print?

const moves = ["Spark", "Thunder"]; moves.forEach((move, i) => console.log(i + ": " + move));
Options
β€’ 0: Spark then 1: Thunder
β€’ 1: Spark then 2: Thunder
β€’ Spark: 0 then Thunder: 1
β€’ undefined: Spark twice

Hint : The second parameter is the position, counted the way arrays count.

Exercise 7 β€” What forEach Doesn't Do

`forEach` always returns `undefined`. It's made for doing something with each element, not for producing a result:

const levels = [5, 8, 3]; const result = levels.forEach((level) => level * 2); console.log(result);

It also can't be stopped early: `break` doesn't work inside a callback. If you need a result or an early exit, use a `for...of` loop, or the methods from the next chapters.

Exercise 8 β€” Numbered Moves

Print each move with its number, starting at 1.

Hint : The second parameter is used in the body, and positions start at 0.

Exercise 9 β€” Quiz: The Return of forEach

What does this code print?

const names = ["Zap", "Metachu"]; const out = names.forEach((n) => n.toUpperCase()); console.log(out);
Options
β€’ undefined
β€’ ["ZAP", "METACHU"]
β€’ ZAP,METACHU
β€’ 2

Hint : This method never produces a value.

Exercise 10 β€” forEach Cheat Sheet

Match each element with its description.

Items to match
β€’ First callback parameter
β€’ Second callback parameter
β€’ What forEach returns
Definitions
β€’ The current element
β€’ The current index
β€’ undefined

Exercise 11 β€” Team Sheet

Print a team sheet from an array of objects, using `forEach` only (no `for` loops).

Step 1: print each member as `"N. name (level X)"`, numbered from 1. Step 2: while doing so, add up the levels in a `total` variable. Step 3: after that, print `"Average level: X"` where X is the total divided by the number of members.

Expected output:

1. Aquachu (level 12) 2. Pyrochu (level 8) 3. Zap (level 4) Average level: 8
Starter code
const team = [ { name: "Aquachu", level: 12 }, { name: "Pyrochu", level: 8 }, { name: "Zap", level: 4 } ]; // Write your code here
Back to the course