JS: for-in Loop πŸ‘Ž

By Xah Lee. Date: . Last updated: .
for (key in obj) { body }

Sets the property name to key in body.

🟒 tip: for-in loop is not good because it goes thru the Prototype Chain. by default, Object.prototype don't have enumerable properties, that is why it doesn't show odd properties such as β€œtoString” in Object.prototype.toString. Better is to use Object.keys and forEach.

const xdad = { dog: 1 };
const xson = { cat: 1 };

// make xdad to be the parent of xson.
Reflect.setPrototypeOf(xson, xdad);

// for-in loop on xson
for (let kk in xson) console.log(kk);

// cat
// dog

// result also shows keys from parent