For...In Loops
A for...in loop visits the names of an object’s enumerable properties, one per pass. It is a way to walk through the keys of a plain object. For arrays and other lists, use for...of instead, for the reasons below.
Looping over an object
Section titled “Looping over an object”On each pass, the loop variable holds one property name as a string. Use bracket notation to read the value, because the name is held in a variable:
const capitals = { France: 'Paris', Japan: 'Tokyo', Kenya: 'Nairobi' };
for (const country in capitals) { console.log(`${country}: ${capitals[country]}`);}This prints:
France: ParisJapan: TokyoKenya: NairobiDeclare the loop variable with const or let. Leaving the declaration out, as in for (country in capitals), creates an accidental global variable in sloppy mode and throws a ReferenceError in strict mode and in modules.
The order of the keys
Section titled “The order of the keys”The keys come in a fixed order. Keys that look like whole numbers come first, in ascending numeric order, and the other string keys follow in the order they were added:
const shelf = { b: 'second', 10: 'ten', a: 'first', 2: 'two' };
for (const key in shelf) { console.log(key, typeof key);}This prints:
2 string10 stringb stringa stringEvery key is a string, even one written as a number.
Inherited properties
Section titled “Inherited properties”for...in also visits enumerable properties that the object inherits through its prototype. Here settings inherits colour from defaults:
const defaults = { colour: 'blue' };const settings = Object.create(defaults);settings.size = 'large';
for (const key in settings) { console.log(key);}
for (const key in settings) { if (Object.hasOwn(settings, key)) { console.log('own:', key); }}
console.log(Object.keys(settings));This prints:
sizecolourown: size[ 'size' ]Object.hasOwn() filters out the inherited keys. Object.keys() returns only the object’s own enumerable keys, so it avoids the question altogether. Plain objects created with {} inherit nothing enumerable, so this matters mainly for objects built with Object.create(), classes or older libraries that add to built-in prototypes.
Why not for arrays
Section titled “Why not for arrays”An array is an object whose keys are its indexes, so for...in does run over an array, but it brings two problems. The index arrives as a string, and any extra property on the array is visited too:
const scores = [80, 65, 92];scores.note = 'mock exam';
for (const i in scores) { console.log(`Question ${i + 1}: ${scores[i]}`);}This prints:
Question 01: 80Question 11: 65Question 21: 92Question note1: mock exami + 1 joins strings instead of adding numbers, and the note property is treated as a question. A for...of loop or a plain for loop has neither problem.
Object.entries as an alternative
Section titled “Object.entries as an alternative”To loop over an object’s keys and values together, Object.entries() returns an array of [key, value] pairs, which for...of can unpack:
const capitals = { France: 'Paris', Japan: 'Tokyo', Kenya: 'Nairobi' };
for (const [country, city] of Object.entries(capitals)) { console.log(country, city);}This prints:
France ParisJapan TokyoKenya NairobiMany developers prefer this form even for plain objects, because it skips inherited keys and gives the value without a second lookup. Keys, values and entries covers these methods.
Steve Griffith covers this topic in his video JavaScript for..in Loops.