JavaScript: for-in Loop

By Xah Lee. Date: . Last updated: .

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 Property Attributes]

// 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

Tip: don't use for-in loop, because you probably don't want to go thru parent chain. Use Object.keys to get a array then use array method forEach .

See also:

JavaScript Property

βˆ‘ JS in Depth
XAH Β BUY NOW

JS in Depth

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc