JavaScriptFundamental (ES6), part 1
for...in on arrays and inherited keys in JavaScript
51 for...of against for...in
easyLoop over the same array with for...of and for...in and report what each one yields, including the type of what for...in gives you. Add a stray property and a hole to the array, then try for...of over a plain object.
Stuck? Three hints, smallest first
- 1.
for...ofasks for the values through the iterator.for...inlists enumerable keys. - 2. Array indices are string keys, and
for...inalso walks the prototype chain and any extra property. - 3. A plain object has no
Symbol.iterator, sofor...ofover one throws.
const areas = ['Ikeja', 'Yaba', 'Lekki'];
areas.note = 'stray property';
const values = [];
for (const area of areas) values.push(area);
const keys = [];
for (const key in areas) keys.push(key);
const keyTypes = keys.map((k) => typeof k);
const sparse = [1, , 3]; // one hole in the middle
const ofSparse = [];
for (const v of sparse) ofSparse.push(v === undefined ? 'hole' : v);
const inSparse = [];
for (const i in sparse) inSparse.push(i);
const parent = { inherited: 'from the prototype' };
const child = Object.create(parent);
child.own = 'mine';
const inChild = [];
for (const key in child) inChild.push(key);
const attempt = (fn) => { try { return fn(); } catch (e) { return e.constructor.name; } };
const overObject = attempt(() => {
const out = [];
for (const v of { a: 1 }) out.push(v);
return out;
});
console.log('for...of :', values);
console.log('for...in :', keys, '| types:', keyTypes);
console.log('sparse : of ->', ofSparse, '| in ->', inSparse);
console.log('inherited: for...in ->', inChild, '| Object.keys ->', Object.keys(child));
console.log('for...of over a plain object:', overObject);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('for...of yields the values', values, ['Ikeja', 'Yaba', 'Lekki']);
test('for...in yields every enumerable key, the stray one included', keys, ['0', '1', '2', 'note']);
test('and those keys are strings, not numbers', keyTypes, ['string', 'string', 'string', 'string']);
test('for...of visits a hole as undefined', ofSparse, [1, 'hole', 3]);
test('for...in skips the hole entirely', inSparse, ['0', '2']);
test('for...in walks the prototype chain', inChild, ['own', 'inherited']);
test('Object.keys stops at own keys', Object.keys(child), ['own']);
test('for...of over a plain object throws, because it is not iterable', overObject, 'TypeError');
test('the array length ignores the stray property', areas.length, 3);
for...in is not the array loop. Three assertions here say why: it hands you '0' rather than 0, so key + 1 is '01'; it includes anything else enumerable on the object, including a property a library added; and it climbs the prototype chain. It exists for objects, and even there Object.keys or Object.entries is usually what you meant.
The hole is the sharpest difference. [1, , 3] has no key '1' at all, so for...in jumps from '0' to '2' while for...of reports three values with the middle one undefined. That is the iterator protocol counting to length rather than consulting the keys — which is also why for...of is the loop that agrees with length.