Strings iterate by character, not by code unit
length counts UTF-16 code units; the string iterator steps by code point. entries() returns another iterator, of [index, value] pairs.
An iterable is any object with a Symbol.iterator method that returns an iterator: an object whose next() hands out { value, done } results one at a time. for...of, spread, destructuring and Array.from all speak this protocol, so you can make your own objects work with them.
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.
Make an object letters with a [Symbol.iterator] that yields "a", "b", "c" (write next() by hand, no generator), and log [...letters].
Write take(iterable, n) that returns an array of the first n values of any iterable, and closes it properly. Test it with take("hello", 2).
Explain it without notes
What is the difference between an iterable and an iterator?
Walk through what the engine does when it runs for (const x of obj).
When is an iterator's return() method called, and why does it exist?
Why are plain objects not iterable, and how do you loop over them?
Preview
Console
Nothing logged yet.Expected console output
4
3
[ 'h', 'i', '😀' ]
0 h
1 i
2 😀