JavaScript: Loops

Repeat work with for, while, and modern iteration patterns.

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

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

  1. Sum numbers 1–100 with a loop.
  2. Iterate an array with for…of and build a new string.
  3. Loop object keys with for…in and log key-value pairs.

Next up

Quick Check

Which loop iterates over the values of an array?