The for loop
A for loop has three parts: where to start, when to keep going, and how to move on.
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Output:
1
2
3
4
5
i++ means "add 1 to i". A multiplication table:
for (let i = 1; i <= 5; i++) {
console.log(`7 x ${i} = ${7 * i}`);
}
Output:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
Adding up
let total = 0;
for (let n = 1; n <= 10; n++) {
total += n;
}
console.log(total);
Output:
55
The while loop
let count = 3;
while (count > 0) {
console.log(count);
count--;
}
console.log("Go!");
Output:
3
2
1
Go!
A while loop must eventually make its condition false. If it never does, it runs forever and freezes the page.
break and continue
for (let n = 1; n < 10; n++) {
if (n % 2 === 0) continue;
if (n > 7) break;
console.log(n);
}
Output:
1
3
5
7
Try it yourself
- Print the even numbers from 2 to 20.
- Add up the numbers 1 to 100.
- Print a countdown from 10 to 1.
Next lesson: arrays and objects.

Comments
Loading comments…