Sub topic 2
Looping over Keys with Object.keys
This chapter assumes you know JavaScript variables, arrow functions, object literals, dot and bracket property access, arrays, and the for...of loop. It also builds on the previous chapter's idea of own enumerable string-keyed properties: the properties defined directly on an object, visible to enumeration, whose keys are strings.
Object.keys is the usual starting point for looping over a plain object. It turns the object's keys into an ordinary array. You can then loop over that array with any tool that works on arrays.
What Object.keys Returns
Object.keys(obj) returns a new array that holds the object's own enumerable string keys. It does not return values, and it does not give you an iterator or a live view of the object. You get a plain array of strings.
const scores = { alice: 90, bob: 72, carol: 85 };
const names = Object.keys(scores);
console.log(names); // [ 'alice', 'bob', 'carol' ]
console.log(Array.isArray(names)); // true
console.log(names.length); // 3Because the result is a real array, everything you know about arrays applies to it. You can read its length, index into it, loop over it with for...of, or call array methods on it. Later chapters cover the array methods.
The Basic Pattern: for...of plus Bracket Notation
This is the standard loop:
const scores = { alice: 90, bob: 72, carol: 85 };
for (const name of Object.keys(scores)) {
console.log(name, scores[name]);
}
// alice 90
// bob 72
// carol 85The loop works in two steps:
Object.keys(scores)runs once, before the loop starts, and produces['alice', 'bob', 'carol'].for...ofwalks that array. On each pass,nameholds one key, andscores[name]looks up the matching value.
Declare the loop variable with const. Each pass gets a fresh binding, so const works, and it stops you from reassigning the key by accident inside the loop body.
Why Bracket Notation and Not Dot Notation
Dot notation such as scores.name reads the property whose key is literally "name". Bracket notation such as scores[name] evaluates the variable name first and then looks up whatever key it holds. Inside the loop the key lives in a variable, so you need brackets.
const scores = { alice: 90, bob: 72, carol: 85 };
for (const name of Object.keys(scores)) {
console.log(scores.name); // looks up a property literally called "name"
}
// undefined
// undefined
// undefinedWhy Not Loop over the Object Directly?
Arrays, strings, Maps, and Sets are iterable. That means they define a built-in way for for...of to step through them. Plain objects are not iterable, so passing one straight to for...of throws.
const scores = { alice: 90, bob: 72, carol: 85 };
try {
for (const item of scores) {
console.log(item);
}
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message); // scores is not iterable
}Plain objects are left non-iterable on purpose. An object could reasonably yield its keys, its values, or its pairs, and no single choice is right for every case. Object.keys, Object.values, and Object.entries make you pick one explicitly. This chapter uses keys. The next chapters cover values and pairs.
Keys Are Always Strings
Every key that Object.keys returns is a string, even when you wrote the key as a number in the literal. JavaScript converts non-symbol property keys to strings when it stores them.
const stock = { 101: 'pen', 202: 'ink' };
for (const id of Object.keys(stock)) {
console.log(typeof id, id === '101', id === 101, Number(id) === 101);
}
// string true false true
// string false false falseThis matters in comparisons and arithmetic:
const stock = { 101: 'pen', 202: 'ink' };
for (const id of Object.keys(stock)) {
console.log(id + 1); // string concatenation
console.log(Number(id) + 1); // numeric addition
}
// 1011
// 102
// 2021
// 203If you need numeric keys, convert them with Number(id) inside the loop. If the keys represent numbers throughout your program, a Map may suit you better, because a Map keeps key types as they are.
Useful Things to Do with the Keys Array
The loop isn't the only use for Object.keys. Since the result is an array, some common questions take one line to answer.
Counting Properties
Objects have no length property, but the keys array does:
const scores = { alice: 90, bob: 72, carol: 85 };
console.log(scores.length); // undefined
console.log(Object.keys(scores).length); // 3Checking for an Empty Object
An object literal {} is truthy, so if (obj) can't tell you whether it has properties. Check the key count instead:
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}
console.log(isEmpty({})); // true
console.log(isEmpty({ a: 1 })); // false
console.log(Boolean({})); // true, so a truthiness check is useless hereChecking Whether a Key Is Present
Object.keys(obj).includes(key) works, but it builds a whole array to answer a yes-or-no question. Object.hasOwn(obj, key) gives the same answer for own properties more directly. Use Object.keys when you need the full list, and Object.hasOwn when you only need to test one key.
const scores = { alice: 90, bob: 72 };
console.log(Object.keys(scores).includes('bob')); // true
console.log(Object.hasOwn(scores, 'bob')); // true
console.log(Object.hasOwn(scores, 'dave')); // falseControlling the Loop: break, continue, and Indexes
A for...of loop over the keys array supports break and continue, which array callback methods like forEach do not. That makes it a good fit for searches where you want to stop early.
const scores = { alice: 90, bob: 72, carol: 85, dave: 60 };
let firstBelow75 = null;
for (const name of Object.keys(scores)) {
if (scores[name] >= 75) continue; // skip passing students
firstBelow75 = name;
break; // stop at the first match
}
console.log(firstBelow75); // bobIf you also need the position of each key, call the array's own .entries() method. This is Array.prototype.entries, not Object.entries. It yields [index, key] pairs:
const scores = { alice: 90, bob: 72, carol: 85 };
for (const [i, name] of Object.keys(scores).entries()) {
console.log(`${i + 1}. ${name}: ${scores[name]}`);
}
// 1. alice: 90
// 2. bob: 72
// 3. carol: 85The square brackets in the loop head are array destructuring. A later chapter covers that syntax in detail.
The Keys Array Is a Snapshot
Object.keys reads the object's keys once, at the moment you call it. After that, the array and the object are independent. Adding a property to the object later doesn't add it to the array, and changing the array doesn't change the object.
const scores = { alice: 90, bob: 72 };
const names = Object.keys(scores);
scores.carol = 85;
console.log(names); // [ 'alice', 'bob' ]
console.log(Object.keys(scores)); // [ 'alice', 'bob', 'carol' ]
names.push('zed');
console.log(Object.hasOwn(scores, 'zed')); // falseYou get two consequences from this. You can safely read values through a saved keys array as long as the object's set of keys hasn't changed. And if the object does change, call Object.keys again to get a fresh list. The final chapter uses this snapshot behavior to delete properties safely during a loop.
Common Errors at a Glance
| Symptom | Likely cause | Fix |
|---|---|---|
| `TypeError: obj is not iterable` | `for (const x of obj)` on a plain object | Loop over `Object.keys(obj)` |
| Every value prints as `undefined` | `obj.key` instead of `obj[key]` | Use bracket notation with the variable |
| `id === 101` is never true | Keys are strings | Compare with `'101'` or convert with `Number(id)` |
| Sums come out as `"0102030"` | Adding string keys instead of values | Add `obj[key]`, not `key` |
| `obj.length` is `undefined` | Objects have no length | Use `Object.keys(obj).length` |
| New properties missing from a saved list | The keys array is a snapshot | Call `Object.keys` again |
When Object.keys Is the Right Choice
Use Object.keys when the key itself is what you need: to print labels, build lookups, count properties, test for emptiness, or read each value by name while also using the name. If you only need the values, Object.values (next chapter) skips the lookup step. If you need both key and value on every pass, Object.entries hands you both at once and keeps the loop body shorter.
Exercise
Write a loop using Object.keys that prints only the products whose stock is zero, given const stock = { pens: 12, ink: 0, paper: 40, clips: 0 };. What does it print, and what would it print if you wrote stock.item === 0 instead of stock[item] === 0?
Show answer
for (const item of Object.keys(stock)) { if (stock[item] === 0) console.log(item); } prints ink and then clips. With stock.item, JavaScript looks up a property literally named "item", which doesn't exist, so the value is undefined. undefined === 0 is false on every pass, so nothing prints and no error is raised.
Exercise
Given const rooms = { 3: 'Lab', 10: 'Office', 7: 'Hall' };, a teammate writes let total = 0; for (const n of Object.keys(rooms)) total += n;. What is total afterwards, and how do you make it sum the room numbers to 20?
Show answer
total becomes the string "03710". The keys are strings, so 0 + '3' is '03', and each later += concatenates. The keys come back in ascending numeric order (3, 7, 10) because they are integer-like. Write total += Number(n); to get the numeric sum 20.
Exercise
Write an isEmpty(obj) function and explain why if (!obj) cannot replace it for plain objects.
Show answer
function isEmpty(obj) { return Object.keys(obj).length === 0; }. Every object, including {}, is truthy, so !obj is false for both empty and non-empty objects. Counting own enumerable keys is what tells the two apart.