for...of in depth
Learn how for...of uses the iterator protocol under the hood.
How for...of works
The for...of loop calls the iterable's [Symbol.iterator]() method to get an iterator. Then it calls next() each step, copying the value into the loop variable until done: true comes back. That is why the same syntax works on strings, Map, Set and your own iterables.
Key distinction: for...in walks object keys, while for...of walks values. forEach exists only on built-in collections like arrays, Map and Set, but for...of works on any iterable.
break and continue
Inside for...of you can use break to stop the loop early and continue to skip an iteration. When break is called, the iterator is finalized; JavaScript calls its return() method behind the scenes to clean up.
So for...of is good not just for traversal but also for stopping when a condition is met. forEach does not support break; for early exit you must use for...of.
Exercise Function that counts an iterable
Write a function called countItems that takes an iterable parameter. Inside, declare let count = 0. Loop over the iterable with for...of and do count++ on each item. Then return count. Call the function with an array and a string, and log the results with console.log.
Show example solution
function countItems(iterable) {
let count = 0;
for (const item of iterable) {
count++;
}
return count;
}
console.log(countItems(["apple", "pear", "cherry"]));
console.log(countItems("hello"));
Test yourself
-
Which data type works with for...of but has no forEach method?
- Array
- String
- Map
- Set
Show answer
String — Correct. Strings are iterable but have no forEach method.
-
Complete the for...of loop
const text = "hello"; for (const ch ____ text) { console.log(ch); }Show answer
const text = "hello"; for (const ch of text) { console.log(ch); } -
Which is NOT iterable?
- Array
- String
- Set
- Number
Show answer
Number — Correct. Numbers are not iterable; for...of fails on them.