DEV Community

Cover image for Loop Statement
Janu Nirmal
Janu Nirmal

Posted on

Loop Statement

While loops execute a block of code as long as a specified condition is true.

There are two types of false statement

  1. While loop
  2. For loop

Syntax for loop statement

while (condition) 
{
  // code block to be executed
}
Enter fullscreen mode Exit fullscreen mode

Scenario 1

<!DOCTYPE html>
<html>

<head>
    <title>Loop Statement</title>
</head>

<body>

    <script>

        let count = 1;

        while (count <= 9) {

            document.write(count + "<br>");

            count = count + 2;

        }

    </script>

</body>

</html>
Enter fullscreen mode Exit fullscreen mode

Output

1
3
5
7
9
Enter fullscreen mode Exit fullscreen mode

Scenario 2

<!DOCTYPE html>
<html>

<head>
    <title>Looping Program</title>
</head>

<body>

    <script>

        let num = 1;

        while (num <= 5) {

            document.write(num + "<br>");

            num++;

        }

    </script>

</body>

</html>
Enter fullscreen mode Exit fullscreen mode

Output

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

Scenario 3

<!DOCTYPE html>
<html>

<head>
    <title>While Loop Statement 3</title>
</head>

<body>

    <script>

        let count = 2;

        while (count <= 10) {

            document.write(count + "<br>");

            count = count + 2;

        }

    </script>

</body>

</html>
Enter fullscreen mode Exit fullscreen mode

Output

2
4
6
8
10
Enter fullscreen mode Exit fullscreen mode

Scenario 4

<!DOCTYPE html>
<html>

<head>
    <title>Loop Statement</title>
</head>

<body>

    <script>

        let count = 5;

        while (count >= 1) {

            document.write(count + "<br>");

            count--;

        }

    </script>

</body>

</html>
Enter fullscreen mode Exit fullscreen mode

Output

5
4
3
2
1

Enter fullscreen mode Exit fullscreen mode

Top comments (0)