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">
    <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>
    <div id="res"></div>
        var x = document.getElementById("res");
            var sum = 0;
            var i = 0;
            do {
                sum += i;
        while (i < 5);
        x.innerHTML = sum;

Post a Comment