Sub topic 1
Two Loops, Two Questions: Keys or Values?
JavaScript has two loops that look almost the same and do different jobs. for...in asks "what are this object's property keys?" for...of asks "what values does this collection produce?" If you know which question you are asking, you can pick the right loop.
Prerequisites
This chapter assumes you know:
- variables declared with
letandconst - objects, arrays and bracket property access (
obj[key]) - functions and arrow functions
for...in: Walking an Object's Property Keys
for...in gives you each property key as a string. To get the value, you read it with bracket access.
const user = { name: 'Ada', role: 'admin' };
for (const key in user) {
console.log(key, user[key]);
}
// name Ada
// role adminEnumerable Properties: What for...in Sees and Skips
for...in only visits enumerable string-keyed properties. A property is enumerable when its enumerable flag is true, which is the default for properties you create by assignment. It skips properties whose flag is false, such as an array's length, built-in methods, or anything defined with Object.defineProperty without enumerable: true. It also skips Symbol keys.
const item = { visible: 1 };
Object.defineProperty(item, 'hidden', { value: 2, enumerable: false });
item[Symbol('id')] = 3;
for (const key in item) console.log(key);
// visibleInherited Properties and Filtering with Object.hasOwn
People often forget that for...in also visits enumerable properties it finds on the prototype chain. Use Object.hasOwn to keep only the object's own properties.
const base = { shared: true };
const obj = Object.create(base);
obj.own = 1;
for (const key in obj) {
console.log(key, Object.hasOwn(obj, key));
}
// own true
// shared falseThe Order of Property Keys
for...in and Object.keys use the same order for own properties. Keys that look like integers come first, in ascending numeric order. All other string keys follow in the order you added them.
const o = { b: 1, 2: 'two', a: 2, 1: 'one' };
console.log(Object.keys(o));
// ['1', '2', 'b', 'a']for...of: Walking the Values of an Iterable
for...of works on iterables. An iterable is an object that knows how to produce a sequence of values. Arrays, strings, Maps and Sets are all iterables. The loop gives you the values themselves and ignores property keys.
const colors = ['red', 'green'];
for (const color of colors) {
console.log(color);
}
// red
// greenExercise
Given const child = Object.create({ a: 1 }); child.b = 2; child[5] = 'x'; what does for (const k in child) console.log(k) print, and how do you print only own keys?
Show answer
It prints '5', 'b', 'a'. The own keys come first: the integer-like '5', then 'b'. The inherited 'a' comes last. To print only own keys, wrap the log in if (Object.hasOwn(child, k)).