TutreNews Learn

Control flow

Loops

Goal: Repeat with for, while and for…of · 9 min

The classic for loop has three parts — start; condition; update:

for (let i = 0; i < 3; i++) { console.log(i); }   // 0 1 2

while repeats as long as a condition holds. for…of iterates over the values of an array or string — usually the clearest choice:

for (const fruit of ["apple", "kiwi"]) { console.log(fruit); }

break exits the loop, continue jumps to the next round. Note: for…in iterates over keys (property names), which is meant for objects — not arrays.

Worked example: Sum of squares

  1. i runs 1, 2, 3, 4.
  2. sum = 1 + 4 + 9 + 16.
  3. Output: 30
let sum = 0;
for (let i = 1; i <= 4; i++) {
  sum += i * i;
}
console.log(sum);

Output:

30