One cabinet read five ways at Bayu’s counter: Object.keys, values, entries, for...in and for...of. Do all five read the same drawers? The browser answers. An…
Why it matters
Reading an object is everyday work: rendering a form, transforming data, counting. Pick the wrong way and inherited keys sneak in, or the loop throws a TypeError. Object.entries with for...of is the safe loop: it destructures into [k, v] and maps easily.
The key idea
Object.* reads own drawers only, for...in climbs the prototype
Common mistakes
for...in without an Object.hasOwn filter It reads inherited keys too. Use Object.keys, or filter with if (Object.hasOwn(obj, k)) inside the loop.
Thinking for...in is for...ofin reads an object’s KEYS; of reads the ITEMS of something iterable, and throws a TypeError on a plain object.
Expecting a random key order The order is fixed: whole-number keys first (ascending), then text keys in the order they came, then symbols (which Object.keys skips).
Try it in this playground
Read an inherited key with for...in for...in climbs into the ghost cabinet and lists it; Object.keys does not.
Mix number keys and text keys Whole-number keys are always read first, ascending.
Use for...of on a plain object A plain object is not iterable: a TypeError. For an object, use Object.entries(o).
Read a Map with Object.* The result is []: a Map’s contents are not drawers (properties).