JavaScript do while loop

 JavaScript do while loop

In JavaScript we use do while loop to execute a particular block of code at least once.

This does not check the condition initially. It executes the block of code followed by the do keyword and then checks the condition.

Let's take a look at a simple example to understand this.

Here we are adding the numbers to sum while variable i is less than 5.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Do while loop</title>
</head>
<body>
    <div id="res"></div>
    <script>
        var x = document.getElementById("res");
            var sum = 0;
            var i = 0;
            do {
                sum += i;
            i++;
        }
        while (i < 5);
        x.innerHTML = sum;
    </script>
</body>
</html>



Post a Comment

0 Comments

React