Press ESC to close

JavaScript for loop

0 1997

In this lesson we will talk about JavaScript for loop and we do some usage examples to better understand how it works.

The for loop is an iterative structure that serves to repeat statements a certain number of times.

JavaScript for loop – syntax

The syntax of the for loop is as follows:



for(expression1; expression2; expression3){
   instructions;
}

Where:

  • expression1 is generally an initialization such as: i = 0.
  • expression2 is a condition, a test that returns a boolean value.
  • while expression3 usually represents an increase or decrease.
  • the instructions inside the curly brackets are executed only if expression2 gives a boolean value true. Otherwise the cycle will not run even once. Furthermore, if expression2 is always true then the instructions inside the curly brackets will be executed indefinitely. It is therefore said that the cycle is infinite.

JavaScript for loop – first example

Display the numbers 1 to 9 using the for loop.

First we start from the first expression which is an initialization. In our case we can use a variable i that starts from 0.

Then, the second expression is our test, that is in our case i <10 as the cycle will have to continue until we arrive at number 9.

The third expression is an increase, in our specific case it is the increase of variable i by 1.

Within the for loop we simply insert a print of the variable i.

Here is the complete code:


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

The output produced by this very simple script are the numbers from 0 to 9.

JavaScript for loop - second example

Display even numbers from 0 to 100.

Even numbers are obtained simply by increasing the initial value 0 by 2, then the increase becomes: i + = 2.

We then always print our variable i.

So here is the easy solution to the proposed algorithm:


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

JavaScript for loop - third example

Display the odd numbers from 1 to 99.

The exercise is similar to the previous one, we just need to change the initialization of variable i.

Here is a possible solution:


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

Conclusion

These are just some examples of exercises with the JavaScript for loop, in the next lessons I will propose many other examples.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts

JavaScript variables and costants

Other stories

JavaScript functions

Next Story

JavaScript do while

Previous Story