JavaScript for Loop

The for loop in JavaScript is used to execute a block of code or group of statements multiple times based on the given/particular condition.

Here is the general form to use for loop in JavaScript:

for(initialization; condition-checker; incrementation)
{
   // block of code, to be executed here
}

Here is the explanation:

  • initialization - This part is used to initialize the loop variable. This part is executed first, after the execution, loop control never executes this part. After executing the initialization part, loop control transfers to the condition-checker part
  • condition-checker - This part is executed to check whether the condition evaluates to true or false. If true, then the loop control transfers to the body of the loop to execute the given block of code, otherwise if false, then the loop exits. Every time loop control transfers to the condition-checker part after incrementation part, except at the first time. At first time, loop control transfers to condition-checker part after initialization part
  • incrementation - This part is executed every time after running the block of code present inside the loop. This part is is to increment or decrement the loop variable

JavaScript for Loop Example

Here is an example illustrates how to use for loop in JavaScript:

<!DOCTYPE HTML>
<html>
<head>
   <title>JavaScript for Loop</title>
</head>
<body>

<h3>JavaScript for Loop Example</h3>
<script type="text/javascript">
   
   var num = 2;
   document.write("Printing the table of " + num + "<br/>");
   var i;
   for(i=1; i<=10; i++)
   {
      document.write(num*i + "<br/>");
   }
   document.write("Done!");
   
</script>

</body>
</html>

Here is the sample output of the above for loop example in JavaScript:

javascript for loop

JavaScript Online Test


« Previous Tutorial Next Tutorial »