Lesson 9 / 38

Loops

for, while, and the two iteration flavors.

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
  • for...in
  • while
Answer

for...in — `for...in` is built specifically for enumerating an object's keys.