Sub topic 1
Two Loops, Two Questions: Keys or Values?
JavaScript has two loops with almost the same syntax: for...in and for...of. They differ by one word, but they answer different questions. for...in asks "what are the property keys of this object?" for...of asks "what values does this collection produce?" Most bugs with these loops come from using one when you meant the other.
Prerequisites
This chapter assumes you already know:
- How to declare variables with
letandconst - How objects and arrays work, including dot and bracket property access
- How to write functions and arrow functions
A later chapter on async iteration also expects basic familiarity with Promises and async/await.
The Same Data, Two Answers
Run both loops over the same array and compare what you get:
const colors = ['red', 'green', 'blue'];
for (const key in colors) {
console.log('in:', key, typeof key);
}
// in: 0 string
// in: 1 string
// in: 2 string
for (const value of colors) {
console.log('of:', value);
}
// of: red
// of: green
// of: bluefor...in gives you the indices as strings, because array indices are property keys and every property key it visits is a string. for...of gives you the elements themselves.
The Working Model
Keep this rule in mind for the rest of the tutorial:
| Loop | Iterates over | Works on | Each step gives you |
|---|---|---|---|
| `for...in` | Enumerable string property keys, including inherited ones | Any object | A key (string) |
| `for...of` | Values produced by an iterable | Iterables: arrays, strings, Maps, Sets and others | A value |
An iterable is an object that knows how to produce a sequence of values one at a time. Arrays, strings, Maps and Sets are built-in iterables. Plain objects like { a: 1 } are not, so for...of throws a TypeError on them.
Common Errors
- Using
for...inon an array to get elements. You get string indices, and you may also pick up extra properties you didn't expect. - Using
for...ofon a plain object. It throwsTypeError: obj is not iterable. - Doing arithmetic on
for...inkeys.key + 1on the key'1'gives'11', not2.
Later chapters explain what makes a property enumerable, why inherited keys show up, and how for...of works internally.
Exercise
Given const pets = ['cat', 'dog'];, what does for (const p in pets) console.log(p + 1); print, and which loop would print cat and dog?
Show answer
It prints 01 and 11, because for...in yields the string keys '0' and '1', and + concatenates strings. for (const p of pets) console.log(p); prints cat and dog.
Exercise
What happens when you run for (const v of { a: 1, b: 2 }) {}?
Show answer
It throws a TypeError because a plain object is not iterable. for...of only works on iterables such as arrays, strings, Maps and Sets.