Loops That Count
A while loop has three parts: a start, a check and a step. You need these three parts together so often that JavaScript gives them one line, the for loop:
for (let k = 1; k <= 5; k++) {
console.log(k);
}
Output:
1
2
3
4
5
The three parts sit inside the parentheses, separated by semicolons:
for (let k = 1; k <= 5; k++)
---------- --------- ----------
start: check: step:
runs once runs before runs after
each pass each pass
It works exactly like the while loop from the last lesson, but it is easier to read. All three parts are in one place, so you can see at a glance how many times the loop runs. Also, k is declared inside the loop header, so it exists only inside the loop. Using k after the loop gives the error ReferenceError: k is not defined.
There are two common ways to count:
for (let i = 1; i <= n; i++)counts from 1 to n.for (let i = 0; i < n; i++)counts from 0 to n - 1.
Both run exactly n times. The second one, with 0 and <, is common when you work with positions in a list, because positions start at 0 in JavaScript. Lists (called arrays) come in the Arrays section.
You can also count down, or move by more than 1:
for (let i = 10; i >= 0; i -= 2) {
console.log(i);
}
Output:
10
8
6
4
2
0
Here is a loop like the one in the exercise. It prints the first three lines of the 7 times table:
const n = 7;
for (let i = 1; i <= 3; i++) {
console.log(`${n} x ${i} = ${n * i}`);
}
Output:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
Notice what changes on each pass (i and the product) and what stays the same (n).
JavaScript has other kinds of for loops too. The next lesson shows for...of, which is simpler when you do not need a counter.
In the exercise, read n and print its times table from 1 to 10.