Lesson 9 / 40
Loops
Repeat code with for, while and do-while loops and iterate with for-of and for-in correctly.
for, while, do...while
for fits a known count; while fits an unknown one; do...while always runs at least once.
for (let i = 0; i < 3; i++) console.log(i);
let n = 3;
while (n > 0) {
console.log(n);
n--;
}for...of vs for...in
for...of iterates values (arrays, strings); for...in iterates keys (object properties).
const arr = [10, 20, 30];
for (const val of arr) console.log(val);
const obj = { a: 1, b: 2 };
for (const key in obj) console.log(key, obj[key]);break & continue
break exits the loop entirely; continue skips to the next iteration without exiting.
Quick check: Which loop is best for iterating an object's own property keys?
- for...of
- while
- do...while
- for...in
Answer
for...in — `for...in` is built specifically for enumerating an object's keys.