JavaScript Tutorial

Loops In JavaScript
Previous Home Next

JavaScript performs several types of repetitive operations, called "looping" In JavaScript Loops are used to execute the same block of code a specified number of times or while a specified condition is true or false

There are different types of loops used in JavaScript

  • for loop
  • while loop
  • do-while loop
  • for-in loop

for loop :

The for loop is used when user know in advance how many times loop should be run, and it also iterates the elements for the fixed number of times mostly,

Syntax
for ( initialization; condition; increment)  
{  
     javascript code to be executed  
}  

 

initialization is executed before the loop (the code block) starts

condition condition defines for running the loop (the code block)

increment is executed each time after the loop (the code block) has been executed.

Example :

<html>
<body>
<script>
for (i=0; i<=5; i++)
{
document.write("The number is " + i)
document.write("<br />")
}
</script>
</body>
</html>

Output:

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

While loop :

The purpose of a while loop is used when you want the loop to continue until a certain condition becomes true. the while loop is another commonly loop used after the For loop.

Syntax

while (condition)  
{  
  javascript code to be executed  
}  

Example :

<html>
<head>    
<script>  
   
   var i=10;
   while ( i<=15 )  
    {  
    document.write("The number is " + i )
    document.write("<br />")
   
    i++
    }  
    </script>  

<head>
<html>

Output :

The number is 10
The number is 11
The number is 12
The number is 13
The number is 14
The number is 15

Do while loop :

The do while loop is similar to the while loop but here the condition check at the end of the loop, this loop will execute the block of code once, before checking if the condition is true or false,

Syntax

do {
    javascript code to be executed
}
while (condition);

Example :

<html>
<head>
<script>  
    var i=19;  
    do
{  
    document.write("The number is"  +i);
    document.write("<br/>");
    i++;  
    }
while (i<=25);  
    </script> 
<head>
<html> 

Output :

The number is19
The number is20
The number is21
The number is22
The number is23
The number is24
The number is25

for-in loop :

The for..in loop iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.

Syntax

for (variable in object) {...
}

variable- A different type property name is assigned to variable on each iteration.

object - A object whose enumerable properties iterated.

Previous Home Next

Tolal:0 Click:

Show All Comments

Did not find what you were looking for leave your name and message. We will revert within 24 hours
Name:
eMail:
Comment / Feedback: