The for Loop
Most loops count through a series of numbers: from 1 to 10, or through the indexes of an array. In a while loop, the counting is spread over three places: the variable is created before the loop, the condition is at the top, and the change is at the end of the block. The for loop puts all three on one line, so you can see at a glance how the loop counts:
for (let i = 1; i <= 3; i++) {
console.log(i);
}This prints:
1
2
3It does exactly the same as this while loop:
let i = 1;
while (i <= 3) {
console.log(i);
i++;
}The parentheses after for hold three parts separated by semicolons:
let i = 1is the start. It runs once, before the first iteration, and creates the counteri.i <= 3is the condition. It is checked before each iteration. While it is true, the block runs; once it is false, the loop ends.i++is the step. It runs after each iteration and moves the counter on.
So the order is: start, condition, block, step, condition, block, step… until the condition is false. The parts are separated by semicolons, not commas. With commas, you get a SyntaxError.
The counter is usually called i (for “index”), but any name works. The step can be any change: i += 2 counts by twos, and i-- counts down:
for (let i = 3; i > 0; i--) {
console.log(i);
}3
2
1Why let and not const? The counter is a single variable that the step changes after every iteration: i++ changes it from 1 to 2, and then to 3. A const can't be changed, so for (const i = 1; i <= 3; i++) prints 1 and then stops with TypeError: Assignment to constant variable.
Which loop should you choose? for when you know how many times the loop will run: from 1 to 10, or once for each element of an array. while when you don't know in advance, for example to keep doubling a number until it is greater than 1000:
let number = 1;
let doublings = 0;
while (number <= 1000) {
number = number * 2;
doublings++;
}
console.log("Doublings:", doublings);
console.log("Number:", number);Doublings: 10
Number: 1024Instructions
Rewrite the while loop in the editor as a for loop, and delete the while loop. The program still prints the numbers from 1 to 5.
Change your for loop so that it prints the numbers from 15 to 20, including 20.