Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 5.7 — forEach and Iteration Choices
JavaScript · Example 3 of 3

Why not for...in on arrays

for...in gives property names as strings, and includes the extra property. for...of gives exactly the array's values.

You can walk through an array with a classic for loop, for...of, forEach or map; forEach runs a function for each item and returns nothing, can't be stopped early, and is the wrong choice when you need break, a result array, or await.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Print each name in ["Asha", "Ravi", "Meera"] as 1. Asha, 2. Ravi, 3. Meera using for...of and entries().

02

Loop over [3, 7, -2, 9] and stop at the first negative number, printing Negative at index 2.

Explain it without notes

01

What is the difference between forEach and map?

02

How do you stop looping through an array early?

03

Why shouldn't you use forEach with async callbacks when order or completion matters?

04

Why is for...in a poor choice for arrays?

Why not for...in on arrays

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

in: 0 string
in: 1 string
in: extra string
of: a
of: b