for...in on objects (and why not on arrays)
for...in gave string keys ("0" + 1 is "01") and the extra label property. for...of gave exactly the three values.
for...of walks through the values of anything iterable (arrays, strings, Maps, Sets), while for...in walks through the property names (keys) of an object, including inherited ones. Use for...of for lists and Object.keys/entries with for...of for objects.
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 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Given const prices = { tea: 20, coffee: 35, juice: 50 };, print each item and price as tea: 20 and then the total.
Count the vowels in the string "Hectal teaches JavaScript" with for...of.
Print each item of ["a", "b", "c"] with its position starting from 1, like 1. a.
Explain it without notes
What is the difference between for...of and for...in?
Why shouldn't you use for...in to loop over an array?
How do you loop over the keys and values of a plain object?
What does "iterable" mean? Name four built-in iterables.
Console
(nothing was printed)Expected console output
name -> Asha
age -> 30
city -> Pune
1 2 b a
0 string 01
1 string 11
2 string 21
label string label1
10
20
30