🟨 JavaScript Intermediate

What is the difference between for...in and Object.keys()?

Answer

Both iterate over object keys but with an important difference. for...in iterates over ALL enumerable properties of an object, including inherited ones from the prototype chain. This can be surprising: Object.prototype.customProp = "test"; for (const key in {}) console.log(key) would log "customProp" even for empty objects. Always use hasOwnProperty guard: if (obj.hasOwnProperty(key)). Object.keys(obj) returns ONLY the object's own enumerable property names as an array — no inherited properties, no non-enumerable properties. It is safe without a hasOwnProperty check. Related: Object.values(obj) returns own enumerable values; Object.entries(obj) returns [key, value] pairs. Object.getOwnPropertyNames(obj) returns all own properties including non-enumerable ones. Reflect.ownKeys(obj) returns all own keys including Symbols. Best practice: prefer Object.keys()/values()/entries() over for...in for plain object iteration.