JavaScript while loop

 JavaScript while loop

In JavaScript we use loops to run the same code multiple times until a condition is met. 
While loop is the simplest, it runs a block of code until a condition is true. Once the condition fails it exists the loop.

In this example, we are populating a numbered array called numberArray, and pushing an element to it until the value is less than or equal to 10. We also print the same to res div.

<!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>Iterate using while loop</title>
    <div id="res"></div>
        var res = document.getElementById("res");

        var numberArray = [];
        var i = 1;
        while(i <= 10) {
        var x = numberArray.push(i);
        res.innerText += "\n" + x;

Assignment: Try to have five names in an array or object and print them to res block.

Post a Comment