Skip to main content

JavaScript Array forEach — exercises and bug fixes

5 hands-on exercises and 5 find-the-bug challenges for the JavaScript Array forEach lesson. Every one is checked automatically in the browser — write the code, run it, and the tests tell you what still fails.

Exercises(5)

  1. 1

    Build a string with forEach

    easy10 min

    Use forEach to build a dash-separated string of the values.

  2. 2

    Add up with forEach

    easy10 min

    Use forEach to total a list of numbers.

  3. 3

    Use the index

    easy10 min

    Number each name starting at 1, separated by spaces.

  4. 4

    Count matching values

    easy10 min

    Use forEach to count how many numbers are above 10.

  5. 5

    Show forEach returns nothing

    medium10 min

    Store the result of forEach and show its type.

Find the bug(5)

  1. 1

    Fix the result of forEach being used

    easy8 min

    forEach returns nothing, so the doubled values were lost.

  2. 2

    Fix the total declared inside

    easy8 min

    Declaring the total inside the callback resets it every time.

  3. 3

    Fix the arguments in the wrong order

    easy8 min

    The value comes first and the index second, so the labels came out backwards.

  4. 4

    Fix the numbering starting at zero

    easy8 min

    The list should be numbered from 1.

  5. 5

    Fix the early exit that never happens

    easy8 min

    return inside forEach only skips one turn, so the count keeps rising.

Ready to write the code?

The editor, the automatic checks and the worked solutions open up with an account.

Open the workspace