JS: for-in Loop

JS: for-in Loop

for (key in obj) { body }

Loop thru all enumerable string property keys of obj , and will go up to the prototype chain. Sets the property name to key in body.

[see JS: Property Attributes, writable, enumerable, configurable]

Does not include symbol key properties.

[see JS: Symbol Tutorial]

Order is not guaranteed by the spec, but browsers use order of property creation.

// loop thru enumerable properties in prototype chain or own

const o1 = {x1:3};

// create object o2, with parent o1
const o2 = Object.create(o1);

o2.x2 = 4;

for (let kk in o2) { console.log( kk ); }

// prints
// x2
// x1

// it prints x1 because that's a property in parent object

Don't Use For-In Loop

Avoid using for x in obj because you probably don't want to go thru prototype-chain.

Use Object.keys() [see JS: Object.keys]

to get a array then use array method foreach.

[see JS: List Properties]

[see JS: Array.prototype.forEach]

for-of Loop

[see JS: for-of Loop]

Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.