Loops (for / while)
A for loop repeats a block a set number of times, useful when you know how many iterations you need, like stepping through
an array. A while loop repeats as long as a condition stays
true, useful when you don't know the count in advance.
Example 1: for, a known number of steps
let result = "";
for (let i = 1; i <= 5; i++) {
result += i + " ";
}
document.getElementById("output").textContent = "Counted: " + result;
The three parts inside the parentheses run in a fixed order: the
starting value (let i = 1) runs once, the condition
(i <= 5) is checked before every loop, and the update
(i++) runs after every loop, this exact three-part shape is
one of the most common patterns you'll write in any C-family language,
not just JavaScript.
Example 2: while, an unknown number of steps
let total = 0;
let n = 1;
while (total < 20) {
total += n;
n++;
}
document.getElementById("output").textContent = "Total reached: " + total;
Here we don't know in advance how many additions it'll take to reach
20, while is the right tool exactly when the stopping
condition depends on something computed as you go, not a fixed count you
already know.