Sub topic 1
Two Loops, Two Questions: Keys or Values?
JavaScript has two loops that look almost the same: for...in and for...of. They differ by one word, and they answer different questions about your data. for...in asks "what are the names of this object's properties?" for...of asks "what values does this collection produce, one after another?" Most bugs with these loops come from asking one question when you meant the other.
This chapter sets up that mental model. Later chapters cover the details: enumerability, inheritance, key order, the iterator protocol and async iteration.
Prerequisites
This chapter assumes you are comfortable with the following:
- Declaring variables with
letandconst. - Creating objects and arrays, and reading properties with dot access (
obj.name) and bracket access (obj[key]). - Writing functions and arrow functions.
- Reading
console.logoutput in Node.js or a browser console.
A later chapter on for await...of also expects a basic understanding of Promises and async/await. You don't need that here.
The Two Questions
Every collection-like value in JavaScript can be described in two ways.
- By its property keys. An object is a set of named slots. An array is also an object, and its slots are named
"0","1","2"and so on.for...inwalks these names. - By the values it yields. Some values are iterable, which means they know how to hand out a sequence of values on request. Arrays, strings, Maps and Sets are iterable.
for...ofwalks that sequence.
These two descriptions often look alike, which is why the loops get confused. On an array, the keys are positions and the values are elements, and both have a natural order. On other data they come apart completely.
Seeing Both Loops on the Same Array
Run both loops over one array and compare the output:
const colors = ['red', 'green', 'blue'];
for (const key in colors) {
console.log(key, typeof key);
}
// 0 string
// 1 string
// 2 string
for (const value of colors) {
console.log(value, typeof value);
}
// red string
// green string
// blue stringfor...in gave you the indices, and they are strings, not numbers. Property keys in JavaScript are always strings (or Symbols, which for...in ignores). for...of gave you the elements themselves.
To get an element from for...in you must look it up:
const colors = ['red', 'green', 'blue'];
for (const key in colors) {
console.log(colors[key]);
}
// red
// green
// blueThis works, but it takes the long way around. A later chapter explains why for...in is a poor fit for arrays in general.
Seeing Both Loops on a Plain Object
Now try a plain object literal:
const book = { title: 'Dune', year: 1965 };
for (const key in book) {
console.log(key, book[key]);
}
// title Dune
// year 1965
try {
for (const value of book) {
console.log(value);
}
} catch (err) {
console.log(err instanceof TypeError, err.message);
}
// true book is not iterablefor...in works on any object because every object has property keys. for...of throws a TypeError because a plain object does not define a sequence of values. JavaScript cannot guess whether you want keys, values or pairs, so it refuses. (The exact message varies by engine. Node.js and Chrome print "book is not iterable".)
Seeing Both Loops on a String
Strings are iterable, and they also have index keys:
const word = 'hey';
for (const key in word) {
console.log(key);
}
// 0
// 1
// 2
for (const ch of word) {
console.log(ch);
}
// h
// e
// yThe two loops line up for plain ASCII text. They diverge for characters such as emoji, which a later chapter on code points covers.
The Working Model
Each loop gets its data from a different source:
for...inasks the object for its enumerable string property keys, including keys inherited through the prototype chain. It works on any object, and on primitives that JavaScript wraps in an object, such as strings.for...ofasks the value for an iterator, then pulls values from that iterator until it says it is done. It only works on iterables, and throws on anything else.
Here is how the two loops compare across common data types:
| Data | `for...in` gives | `for...of` gives |
|---|---|---|
| Plain object `{a: 1}` | `"a"` | TypeError |
| Array `[10, 20]` | `"0"`, `"1"` (plus any extra enumerable keys) | `10`, `20` |
| String `"hi"` | `"0"`, `"1"` | `"h"`, `"i"` |
| Map `new Map([['k', 1]])` | nothing (entries are not properties) | `['k', 1]` |
| Set `new Set([1, 2])` | nothing | `1`, `2` |
The Map and Set rows show most clearly that the two loops are unrelated. A Map stores its entries internally, not as properties, so for...in finds nothing to report:
const m = new Map([['k', 1]]);
let count = 0;
for (const key in m) count++;
console.log(count); // 0
for (const entry of m) console.log(entry);
// [ 'k', 1 ]Common Errors
Treating keys as numbers
Because for...in keys are strings, arithmetic on them goes wrong without any error:
const nums = [5, 10];
let total = 0;
for (const n in nums) {
total += n;
}
console.log(total); // '001'The developer wanted 15. The loop produced 0 + '0', which is '00', and then '00' + '1', which is '001'. Switching to for...of fixes the bug, because n then holds 5 and 10.
Using for...of on a plain object
Writing for (const v of config) on an options object throws at runtime. Use for...in, or one of Object.keys, Object.values and Object.entries with for...of. A later chapter covers those helpers.
Expecting for...in to see Map or Set contents
As the table shows, for...in on a Map or Set runs zero times. The code doesn't crash, so this bug can go unnoticed.
A Quick Decision Rule
Before writing either loop, say out loud what you want:
- "I want the names of an object's properties." Use
for...in, orObject.keys. - "I want the items in this array, string, Map or Set." Use
for...of.
The final chapter refines this rule with classic for loops and forEach. This two-question test covers most everyday cases.
Exercise
What does this code print, and why? const pets = ['cat', 'dog']; for (const p in pets) console.log(p);
Show answer
It prints 0 and then 1. for...in iterates property keys, and an array's keys are its index strings "0" and "1", not the elements 'cat' and 'dog'. Use for (const p of pets) to get the elements.
Exercise
A teammate writes for (const setting of { debug: true, port: 8080 }) { ... } and gets a TypeError. Explain the cause and name two ways to fix it.
Show answer
Plain objects are not iterable, so for...of has no iterator to request and throws. One fix is for (const key in obj) to walk the keys and read values with obj[key]. Another is for (const [key, value] of Object.entries(obj)) to walk key/value pairs with for...of.
Exercise
How many times does the body run in const s = new Set(['a', 'b', 'c']); for (const x in s) console.log(x);? What would for...of print instead?
Show answer
The body runs zero times, because Set members are stored internally and are not enumerable properties of the Set object. for (const x of s) would print a, b and c in insertion order.