4.4 While Loops
In the previous lesson we used a for loop to print every odd number between 0 and 5. The while loop can produce the exact same result with a slightly different shape. The key difference is that a for loop declares its loop variable inline, whereas a while loop expects the variable to be declared outside the loop.
Translating the for loop
let i = 0;
while (i <= 5) {
if (i % 2 !== 0) console.log(i);
i++;
}
We start by declaring i and initializing it to 0. The while statement takes a condition between parentheses; the body runs as long as the condition stays true. Inside the body, the if only prints the value when i is odd, and the final i++ moves us to the next iteration.
- Initialization is done externally, before the loop.
- Condition is checked first; if it's already false, the body never runs.
- Increment is your responsibility inside the body — forgetting it creates an infinite loop.
Note that the i declared outside the while is distinct from the i declared inside a for loop — the latter is scoped to the loop body. We'll cover scope in detail later. In the next video, we'll look at another type of loop in JavaScript.