Javascript For loop

Blue Caves, Zakynthos, Greece

Hi, Loops are good when we want to run the same code over and over again, each time with a different value. The most common use is when we are working with arrays.

for – loops through a block of code a number of times

The syntax of the for loop is this:

for (initialExpression; condition; incrementExpression) {
  // code block to be executed
}

Example

for(let row = 0; row <= 0; row++) {
  console.log('row ==>', row);
}

The flow of the for is:

Our initial expression is a variable declaration with value of 0, after this declaration the flow will go to the condition and will ask: 0 <= 0 ?

Then because 0 is equal to 0 this condition is TRUE then the code block (inside the for) is executed.

And finally the incrementExpression will be executed.

Note: Always remember that the increment Expression will be executed after the block code was executed and NOT before.

Like this steps:

First loop

1) row = 0

2) 0 <= 0 —> TRUE

3) execute the code block

4) 0+1 at this point row will increment to 1

Second loop

1) row = 1

2) 1 <= 0 —-> FALSE

3) No more executions because the condition is FALSE

Result:

By Cristina Rojas.