Skip to content

1.10 Loops -1-

for Loop

Task 1: Display the numbers from 1 to 5 in the console. Make sure to display each number on a separate line.

console.log(1);
console.log(2);
console.log(3);
console.log(4);
console.log(5);

You will get:

1
2
3
4
5

Task 2: Check this code and compare it with the code in task 1.

for(var i=1;i<=5; i=i+1){
    console.log(i);
}

You will get:

1
2
3
4
5

You can see that code in task 1 and task 2 achieves the same very thing. But the code in task 2 is shorter.

Let's understand this code: for() is for loop in JavaScript. It allows us to do repeated tasks. As you can see only the number changes in the console.log(). So we can write console.log() once only, and declare a variable for the number counter, let it be i for(var i=1; ...; ...).

How does for loop work?

  1. We declare the counter variable. By convention, it is called i: for(var i ....)

  2. Then we set the starting value of the counter: for(var i = 1 ....). In our case, it is 1.

  3. Then we tell the loop to keep on repeating the tasks as long as i<=5 satisfies.

  4. At last, we increase the counter value by 1 in each loop repetition i=i+1.

  5. Notice that we separate var i=1, i<=5 and i=i+1 by semicolon ;.

  6. We open a curly bracket {.

  7. We write the tasks we want to repeat console.log(i). The i of every iteration/repetition will be displayed in the console.

  8. we close the curly bracket }

Task 3: Display the numbers from 0 to 10 in the console.

for(var i=0;i<=10; i++){
    console.log(i);
}

You will get:

0
1
2
3
4
5
6
7
8
9
10

Note(1): i++ works as the same as i=i+1.

More Practice

Task 4: Display the numbers 0, 2, 4, 6, 8, 10 in the console.

for(var i=0;i<=10; i=i+2){
    console.log(i);
}

The result will be:

0
2
4
6
8
10

Task 5: Display the numbers 1, 3, 5, 7, 9 in the console.

for(var i=1;i<=10; i=i+2){
    console.log(i);
}

The result will be:

1
3
5
7
9

Task 6 Display the numbers 10, 20, 30, 40 in the console.

for(var i=10;i<=40; i=i+10){
    console.log(i);
}

The result will be:

10
20
30
40

Task 7: Display the numbers 40, 30, 20, 10 in the console.

for(var i=40;i>=10; i=i-10){
    console.log(i);
}

The result will be:

40
30
20
10

Task 8: Display the word "Ali" 15 times in the console.

for(var i=1;i<=15; i++){
    console.log("Ali");
}

You will get Ali displayed 15 times in the console.

Task 9: Create countdown from 10 to 0. Display the result in the console.

countdown 10
countdown 9
....
countdown 0
for(var i=10;i>=0; i=i-1){
    console.log("countdown " + i);
}

The result will be:

countdown 10
countdown 9
countdown 8
countdown 7
countdown 6
countdown 5
countdown 4
countdown 3
countdown 2
countdown 1
countdown 0

Note(2): You can replace i=i-1 by i--. Both of them do the same work.

Task 10: Create a countdown from 15 minutes to 0. Display the result in the console.

for(var i=15;i>=0; i--){
    console.log(i);
}

The result will be:

15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
0