JavaScript

Lesson 6 of 11

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);
}
  1. Start: let i = 1 runs once, before the loop. It makes a counter.
  2. Condition: i <= 3 is checked before each pass. The loop stops when it is false.
  3. Step: i++ runs after each pass. It adds 1 to i. You can also write i += 2 to add 2.

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

  1. Task 1, not checked yet. Use a for loop to print the numbers 1 to 5, one number on each line.

  2. Task 2, not checked yet. In sumTo, add the numbers from 1 to n with a loop, and return the sum. sumTo(4) is 1 + 2 + 3 + 4, which is 10.

  3. Task 3, not checked yet. In countDown, use a while loop to build the text of the numbers from start down to 1, separated by commas. countDown(3) returns '3,2,1'.

  4. Task 4, not checked yet. Print the even numbers from 2 to 10, one on each line. Change the counter by 2 in each pass.

Task 1 of 4

Use a for loop to print the numbers 1 to 5, one number on each line.

All tasks

main.js

Ctrl+Enter runs your code. Ctrl+Shift+Enter checks it. Press Esc, then Tab, to leave the editor.

Output

Press Run to see your result

Your output shows here. Press Run to try your code.