for statement in javascript

for statement in javascript (for loop)

for statement is used to execute the for block statements number of times based on the condition.

It is important to note that the for loop must be handled correctly, because in some cases the condition may always return true then infinite loop will occur. Because of this, for loop won't terminate to the next statement.

Syntax

[] - This symbol denotes optional.

Flowchart

for statement flowchart

Example

Try Yourself

Execution flow of above example

Step 1 - image explanation
  • Variable i is created and value 0 is assigned to it (var i=0).
  • A condition (i<3) is checked, and it is true (0<3).
  • Alert statement in for loop executes (alert(0)).
Step 2 - image explanation
  • i value is incremented by 1(i++).
  • A condition (i<3) is checked, and it is true (1<3).
  • Alert statement in for loop executes (alert(1)).
Step 3 - image explanation
  • i value is incremented by 1(i++).
  • A condition (i<3) is checked, and it is true (2<3).
  • Alert statement in for loop executes (alert(2)).
Step 4 - image explanation
  • i value is incremented by 1(i++).
  • A condition (i<3) is checked, and it is false (3<3).
  • for loop is terminated and execute the next statement (alert("Finished")).