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.
Print each name in ["Asha", "Ravi", "Meera"] as 1. Asha, 2. Ravi, 3. Meera using for...of and entries().
Loop over [3, 7, -2, 9] and stop at the first negative number, printing Negative at index 2.
Explain it without notes
What is the difference between forEach and map?
How do you stop looping through an array early?
Why shouldn't you use forEach with async callbacks when order or completion matters?
Why is for...in a poor choice for arrays?
Preview
Console
Nothing logged yet.Expected console output
in: 0 string
in: 1 string
in: extra string
of: a
of: b