for loop basics

A for loop allows to execute a piece of code several times.

Example 1.0

for(var i =0; i<10; i++)
{
    console.log("I am printing this message 10 times");
}

If the previous code where to run in chrome we could see the following output in the console.

Basic structure of for loop

for(    INITIALIZATION     ;     CONDITION     ;    INCREMENT    )
{
           CODE
}

We have 4 main parts that build the for

  • INITIALIZATION: Executed only one time at all.
  • CONDITION: Executed before the code is executed. (executed several times)
  • CODE: Executed only if CONDITION is meet (executed several times)
  • INCREMENT: Executed after the code is executed. (executed several times)

The following diagram shows how the flow of a for is performed.

so in our original example 1.0 we could spread the parts of the for as follows.

for(var i =0; i<10; i++)
{
    console.log("I am printing this message 10 times");
}

NOTE THAT

  • INITIALIZATION executes only once.
  • the CONDITION will be executed as long as it is meet.
  • Every time the CONDITION is meet, the CODE and the INCREMENT will execute once.

Leave a Reply

Your email address will not be published. Required fields are marked *