We have already seen an example of how to loop through numbers one-by-one.
We can loop over any range of numbers, starting at any number, moving up or down by any increment.
We could start at 5
, move up in increments of 5
, and stop once we get to 30
or above:
let i = 5;
while (i < 30) {
console.log(i);
i += 5;
}
We could start at -3
, move down in increments of -6
, and stop once we get to -21
or below:
let i = -3;
while (i >= -21) {
console.log(i);
i -= 6;
}
Loops give us the flexibility to handle any repeating work with numbers.