Lesson ยท 10 min
Loops
Do it again
A loop runs the same code many times. Loops save you from writing the same line again and again.
The for loop
A for loop has three parts in its parentheses, separated by semicolons:
for (let i = 1; i <= 3; i++) {
console.log('Pass number ' + i);
}
- Start:
let i = 1runs once, before the loop. It makes a counter. - Condition:
i <= 3is checked before each pass. The loop stops when it is false. - Step:
i++runs after each pass. It adds1toi. You can also writei += 2to add2.
Each run of the code in the braces is called a pass, or an iteration.
The while loop
A while loop has only a condition. You make the counter yourself, and you change it inside the loop.
let n = 3;
while (n > 0) {
console.log(n);
n--;
}
If the condition never becomes false, the loop never ends. Here, if you forget n--, the loop runs forever. Absolute Path stops code that runs for too long, but a loop that never ends is always a bug.
Keeping a running total
A common pattern is to make a variable before the loop and change it in each pass:
let total = 0;
for (let i = 1; i <= 3; i++) {
total += i; // the same as total = total + i
}
console.log(total); // 6
Your turn
Some tasks print lines, and some tasks use functions. Do them in order.
Tasks
4 to do
Task 1, not checked yet. Use a
forloop to print the numbers1to5, one number on each line.Task 2, not checked yet. In
sumTo, add the numbers from1tonwith a loop, and return the sum.sumTo(4)is1 + 2 + 3 + 4, which is10.Task 3, not checked yet. In
countDown, use awhileloop to build the text of the numbers fromstartdown to1, separated by commas.countDown(3)returns'3,2,1'.Task 4, not checked yet. Print the even numbers from
2to10, one on each line. Change the counter by2in each pass.
Task 1 of 4
Use a for loop to print the numbers 1 to 5, one number on each line.