Sub topic 1
What Gets Iterated: Own Enumerable Properties
Prerequisites
This chapter assumes you know JavaScript variables, functions, and arrow functions. You should also know object literals, dot and bracket property access, arrays, the for...of loop, and basic array methods such as forEach, map, and filter.
Own and Enumerable Properties
A plain object can't be used directly in a for...of loop, because objects are not iterable. Instead, you ask the object for an array of its keys, its values, or its [key, value] pairs, and then loop over that array.
Object.keys, Object.values, and Object.entries return only the object's own enumerable string-keyed properties:
- Own means the property is defined on the object itself and is not inherited through the prototype chain.
- Enumerable means the property's
enumerableflag istrue. Properties you create with literals or assignment are enumerable by default. - String-keyed means symbol keys are left out.
In everyday code, these rules give you the properties you wrote yourself. They also explain the surprises covered in later chapters.
Looping over Keys with Object.keys
Object.keys(obj) returns an array of key strings. Use bracket notation to look up each value.
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 85Looping over Values with Object.values
When you don't need the keys, Object.values gives you the values directly. This works well for totals and other aggregations.
const scores = { alice: 90, bob: 72, carol: 85 };
const total = Object.values(scores).reduce((sum, s) => sum + s, 0);
console.log(total); // 247Looping over Key-Value Pairs with Object.entries
Object.entries returns an array of two-element arrays in the form [key, value]. Each pair is a plain array, so you can index into it:
const scores = { alice: 90, bob: 72, carol: 85 };
for (const entry of Object.entries(scores)) {
console.log(`${entry[0]}: ${entry[1]}`);
}
// alice: 90
// bob: 72
// carol: 85The next chapter replaces entry[0] and entry[1] with destructuring.
Exercise
Given const stock = { pens: 4, pads: 0, clips: 12 }, write one expression that counts how many items have a stock greater than zero.
Show answer
Object.values(stock).filter(n => n > 0).length, which evaluates to 2. Use Object.values because the keys are not needed.