Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 2.7 — for...of and for...in
JavaScript · Example 1 of 3 ES2015+

for...of over different iterables

The emoji counts as 2 in .length but as one character in for...of. The Set drops the duplicate js.

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.

01

Given const prices = { tea: 20, coffee: 35, juice: 50 };, print each item and price as tea: 20 and then the total.

02

Count the vowels in the string "Hectal teaches JavaScript" with for...of.

03

Print each item of ["a", "b", "c"] with its position starting from 1, like 1. a.

Explain it without notes

01

What is the difference between for...of and for...in?

02

Why shouldn't you use for...in to loop over an array?

03

How do you loop over the keys and values of a plain object?

04

What does "iterable" mean? Name four built-in iterables.

for...of over different iterables ES2015+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

0 apple
1 banana
2 cherry
length: 4 characters: 3
tag js
tag css
pens 12
books 3