Sub topic 2
for...in: Walking an Object's Property Keys
This chapter assumes you already know how to declare variables with let and const, how to create objects and read their properties with dot and bracket notation, and how to write simple functions. It covers the syntax of for...in, what the loop variable holds on each pass, and the mistakes people most often make with it. Which properties the loop includes, what it inherits and in what order it visits keys are each covered in later chapters.
The Shape of the Loop
A for...in loop runs its body once for each property key of an object. On each pass, the loop variable holds the name of the current property.
const user = { name: 'Ada', role: 'admin' };
for (const key in user) {
console.log(key, user[key]);
}
// name Ada
// role adminThe loop head has three parts:
- A declaration or assignment target (
const key), which receives each key in turn. - The keyword
in. - An expression that evaluates to the object being walked (
user).
The loop gives you keys, not values. To get the value, look it up on the object with the key. That is why user[key] appears inside the body.
Bracket Access, Not Dot Access
The most common beginner bug in for...in code is writing user.key instead of user[key].
const user = { name: 'Ada', role: 'admin' };
for (const key in user) {
console.log(user.key); // undefined, undefined
console.log(user[key]); // 'Ada', 'admin'
}Dot notation takes the text after the dot literally. user.key asks for a property whose name is the word "key", and this object has no such property. Bracket notation evaluates the expression inside the brackets first. So user[key] reads the variable key, gets a string like 'name', and then looks up that property.
Every Key Is a String
The loop variable in for...in is always a string, including when you wrote the key as a number in the object literal. JavaScript converts all non-symbol property keys to strings when it stores them.
const byId = { 1: 'Ada', 2: 'Alan' };
for (const id in byId) {
console.log(typeof id, id + 1);
}
// string 11
// string 21Here id + 1 concatenates strings instead of adding numbers. If you need a number, convert it explicitly:
const byId = { 1: 'Ada', 2: 'Alan' };
for (const id in byId) {
const n = Number(id);
console.log(n + 1, byId[id]);
}
// 2 Ada
// 3 AlanNote that byId[id] still works with the string. Looking up byId['1'] and byId[1] finds the same property, because the number is converted to a string anyway.
Symbol-keyed properties never appear in for...in. The loop only yields string keys:
const tag = Symbol('tag');
const item = { label: 'box', [tag]: 'hidden' };
for (const key in item) {
console.log(key);
}
// labelChoosing the Loop Variable Declaration
The left side of in accepts several forms. They differ in scope and in whether you can reassign the variable.
| Form | Example | Notes |
|---|---|---|
| `const` | `for (const k in obj)` | Recommended. Each pass gets a new binding, so `const` is allowed. |
| `let` | `for (let k in obj)` | Use if you reassign `k` inside the body, which is rare. |
| `var` | `for (var k in obj)` | Function-scoped and visible after the loop. Avoid in new code. |
| Existing variable | `for (k in obj)` | Assigns to a variable declared earlier. After the loop it holds the last key. |
| Property target | `for (state.k in obj)` | Legal but uncommon. Each key is written to `state.k`. |
const works here even though the variable gets a new value each time. The variable is never reassigned. The engine creates a fresh binding for every iteration. A later chapter on closures in loops explains why this matters.
let lastKey;
const settings = { theme: 'dark', lang: 'en' };
for (lastKey in settings) {
// body intentionally empty
}
console.log(lastKey); // 'lang'What the Right-Hand Side Can Be
The expression after in is usually a plain object, but other values behave in specific ways:
for (const k in null) console.log('never'); // no output, no error
for (const k in undefined) console.log('never'); // no output, no error
for (const k in 42) console.log('never'); // numbers have no own keys
for (const k in 'hi') {
console.log(k);
}
// 0
// 1With null and undefined, for...in runs zero times. It does not throw. This is different from Object.keys(null), which throws a TypeError. That silence can hide bugs. If a function receives undefined by mistake, a for...in loop over it does nothing, and nothing warns you.
Primitive values are wrapped in their object form first. A string wrapper has index keys ('0', '1', and so on), so you get positions, not characters. A number wrapper has no enumerable keys of its own, so the body never runs.
Practical Patterns
Use for...in when you need to visit each key of an object that works as a record or dictionary. Typical tasks are summing values, building a transformed copy, or searching.
Summing numeric values:
const stock = { apples: 4, pears: 0, plums: 7 };
let total = 0;
for (const fruit in stock) {
total += stock[fruit];
}
console.log(total); // 11Building a new object with transformed values:
const prices = { tea: 2.5, coffee: 3 };
const withTax = {};
for (const item in prices) {
withTax[item] = Math.round(prices[item] * 1.2 * 100) / 100;
}
console.log(withTax); // { tea: 3, coffee: 3.6 }Finding the first key that matches a condition, then stopping:
const inventory = { bolts: 120, nuts: 0, screws: 45 };
let emptyItem = null;
for (const name in inventory) {
if (inventory[name] === 0) {
emptyItem = name;
break;
}
}
console.log(emptyItem); // 'nuts'break and continue work in for...in the same way they do in a classic for loop.
Common Errors at a Glance
| Mistake | Symptom | Fix |
|---|---|---|
| `obj.key` inside the loop | Every value is `undefined` | Use `obj[key]` |
| Arithmetic on the key | `'1' + 1` gives `'11'` | Convert with `Number(key)` |
| Expecting symbol keys | Symbol properties are missing | Use `Object.getOwnPropertySymbols` or `Reflect.ownKeys` |
| Looping over a possibly undefined value | Loop silently does nothing | Validate the input before the loop |
| Expecting characters from a string | You get `'0'`, `'1'`, ... | Use `for...of` on strings |
There is one more trap. for...in can also visit keys the object inherits from its prototype. The next chapters explain which keys count as enumerable, how inherited keys show up, and how to filter them out with Object.hasOwn.
Exercise
What does this code print, and why? const cfg = { mode: 'fast', retries: 3 }; for (const key in cfg) { console.log(cfg.key); }
Show answer
It prints undefined twice. cfg.key looks up a property literally named "key", which does not exist. The loop runs once per key (mode, retries), but the body never uses the variable. Writing cfg[key] would print 'fast' and 3.
Exercise
Given const scores = { 10: 'low', 20: 'high' }, write a for...in loop that logs each key multiplied by 2 together with its value, so the output is 20 low and then 40 high.
Show answer
for (const k in scores) { console.log(Number(k) * 2, scores[k]); }. The keys arrive as the strings '10' and '20'. Multiplication would coerce them to numbers anyway, but converting with Number makes the intent explicit and avoids surprises if you later switch to +.
Exercise
A function runs for (const k in data) { count++; } and returns count. Called with no argument, it returns 0 instead of failing. Why, and how would you make the mistake visible?
Show answer
data is undefined, and for...in over null or undefined runs zero times without throwing. To surface the bug, check the input first, for example: if (data == null) throw new TypeError('data is required'). Another option is Object.keys(data), which throws on undefined.