for...in & for...of Loops in JavaScript
Two specialized loops split the job: for...of iterates values of iterables (arrays, strings, Maps, Sets, generators) — the default choice for element-by-element work. for...in enumerates an object's string keys including inherited ones — meant for plain-object inspection, dangerous on arrays (order, inherited keys, string indexes).
Rule of thumb: for...of for values, Object.keys/entries plus for...of for objects, for...in almost never (lint rules often ban it on arrays). Both pair with break/continue normally.
for...of yields values
for (const x of arr) visits each element — works on any iterable: arrays, strings, Maps, Sets, generators.
for...in yields keys
for (const k in obj) enumerates string keys including inherited — for objects, not arrays.
Never for...in arrays
String indexes, inherited extras, no order guarantee — use for...of, forEach, or classic indexes instead.
Destructure inline
for (const [k, v] of Object.entries(obj)) and for (const [i, x] of arr.entries()) combine traversal with unpacking.
let colors = ["red", "green"];for (const c of colors) { console.log(c);}let user = { name: "Ada" };for (const k in user) { console.log(k, user[k]);}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.