Learn JavaScript
❯ control_flow.for_in_of

for...in & for...of Loops in JavaScript

$concept

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.

$how it works
1

for...of yields values

for (const x of arr) visits each element — works on any iterable: arrays, strings, Maps, Sets, generators.

2

for...in yields keys

for (const k in obj) enumerates string keys including inherited — for objects, not arrays.

3

Never for...in arrays

String indexes, inherited extras, no order guarantee — use for...of, forEach, or classic indexes instead.

4

Destructure inline

for (const [k, v] of Object.entries(obj)) and for (const [i, x] of arr.entries()) combine traversal with unpacking.

$example
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]);
}
Output
red
green
name Ada
1for...of yields each array value in order — red then green.
2for...in yields the object's key name; bracket access reads its value.
3Values loop vs keys loop — the two constructs' jobs made visible.
$use cases
for...of as the default array/string/collection traversal
Object inspection with for...in plus hasOwnProperty guards
entries() destructuring for index-plus-value loops
Banning for...in on arrays via lint rules

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.