Sunday, 24 July 2016

JavaScript Loops(while, do...while, for loop)

Loops
Loops allows us to execute a particular group of statement repeatedly.
The number of times the statements executes depends on the particular condition. Until the condition is true statement will execute.

There are three types of loops

  • while loop
  • do...while loop
  • for loop
while Loop
In while loop condition is checked first, if the condition is true the statements will executes until the condition is not false.
If condition is false in the first iteration the statement will never execute.
Syntax
while(condition)
{
statement 1
}
Example

<!DOCTYPE html>
<html>
<head>
    <title>javaScript while loop</title>
</head>
<body>
    <h1>JavaScript while loop</h1>
    <script>
        var number1 = 4;
        var number2 = 8;
        while (number1 > 0)
        {
            document.write("count : " + number1 + "<br/>");
            number1--;
        }
    </script>
</body>
</html>


do...while loop
In the do...while condition is checked at the last, which means that the statement will execute at least one time.
Syntax
do
{
statement 1
}
while(condition);
Example

<!DOCTYPE html>
<html>
<head>
    <title>javaScript do...while loop</title>
</head>
<body>
    <h1>JavaScript do...while loop</h1>
    <script>
        var number1 = 4;
        var number2 = 8;
        do {
            document.write("count : " + number1 + "<br/>");
            number1--;
        } while (number1 > 0)
    </script>
</body>
</html>



for loop
It allows us to execute statements predefined number of times. Number of iteration in for loop is known before hand.
Syntax
for(initialization_statement; condition; updation_statement)
{
statement 1
}
Example

<!DOCTYPE html>
<html>
<head>
    <title>javaScript for loop</title>
</head>
<body>
    <h1>JavaScript for loop</h1>
    <script>
        var number1;
        for (number1 = 0; number1 < 6; number1++)
        {
            document.write("count :" + number1 + "<br/>");
        }
    </script>
</body>
</html>


0 comments:

Post a Comment