Loading, please wait...

Loops

JavaScript Loops

In JavaScript, Loops are useful in order to execute a block of code for a number of times as long as the desired condition is true.

Loops are beneficial when we execute same code repeatedly and getting the different outputs in different cases.

 

For Loop

The for loop is commonly used when creating a loop. Here, the loop works a number of times according to the conditions.

 

Syntax

for (Statement 1; Statement 2; Statement 3 )
{
  Block of code
}

 

Statement 1 is executed first even before the execution of the loop.

Statement 2 defines the condition or expression for execution of the code.

Statement 3 is executed every time after the looping code is executed.

 

Code:

<html>
<body>
<h2>The For Loop</h2>
<script>
var x;
for(x=1;x<=5;x++)
{
document.write(x + "<br>");
}
</script>
</body>
</html>

In the above example, Firstly var x is declared with an initial value of 1. Secondly, the value of x is checked when its value not equal to 5.

So, it prints the value of x until the value is x<=5. Thirdly, it increments the value of x after every operation.

 

Output: