freecoding.school100% FREE · NO SIGNUP
Script SpringsISSUE #26 of 29

for...in · iterating keys

SparkyVSNaN the Trickster
Sparky saysfor...in iterates an object’s keys (enumerable property names).

for (const key in obj) walks an object's own (and inherited enumerable) keys. Use it for plain objects, but be aware it can pick up inherited properties — guard with Object.hasOwn(obj, key). Don't use for...in on arrays; the order and inherited keys make it the wrong tool.

Power-ups you unlock

NaN the Trickster attacks — common mistakes

Boss battleIterate an object’s own keys with for...in + Object.hasOwn.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre id="o"></pre>
<script>const o={a:1,b:2}; let out=[]; for(const k in o){ if(Object.hasOwn(o,k)) out.push(k+'='+o[k]); }
document.getElementById('o').textContent=out.join(' ');</script></body></html>
▶ Open the interactive comic issue
‹ For Loops · ClassicFor...Of · Iterating Values ›