for
for (let i = 0; i < 3; i++) {
console.log(i);
}
while / do…while
let n = 0;
while (n < 3) {
n++;
}
let k = 0;
do {
k++;
} while (k < 3);
for…of vs for…in
- for…of: values of an iterable (arrays, strings, maps)
- for…in: keys of an object (enumerable properties)
const arr = ['a','b','c'];
for (const v of arr) console.log(v); // 'a','b','c'
const obj = { a:1, b:2 };
for (const k in obj) console.log(k); // 'a','b'
break and continue
for (let i = 0; i < 10; i++) {
if (i === 5) break; // stop loop
if (i % 2 === 0) continue; // skip even
console.log(i);
}
Practice
- Sum numbers 1–100 with a loop.
- Iterate an array with
for…ofand build a new string. - Loop object keys with
for…inand log key-value pairs.
Next up
Quick Check
Which loop iterates over the values of an array?