JavaScript | Looping Examples/Programs

Looping Example/Program in JavaScript: Here, we have some of the looping example/programs to understand the looping in JavaScript.
Submitted by Pankaj Singh, on October 18, 2018

1) Print numbers from 1 to 10 using 'while' loop

<!DOCTYPE html>
<html lang="en">
<head>
    <script>
        var a=1;
        while(a<=10){
            document.write(a+"<br />");
            a++;
        }
    </script>
</head>
<body>
    
</body>
</html>

Output

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

2) Print numbers from 1 to 15 using 'do while' loop

<!DOCTYPE html>
<html lang="en">
<head>
    <script>
        var a=1;
        do{
            document.write(a+"<br />");
            a++;
        }while(a<=15);
    </script>
</head>
<body>
    
</body>
</html>

Output

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15

3) Print numbers from 1 to 20 using 'for' loop

<!DOCTYPE html>
<html lang="en">
<head>
    <script>
        var a;
        for(a=1;a<=20;a++){
            document.write(a+"<br />");
        }
    </script>
</head>
<body>
    
</body>
</html>

Output

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20

4) Print list (set of strings) using 'forEach' loop

<!DOCTYPE html>
<html lang="en">
<head>
    <script>
        var fruits=["apple","mango","banana","guava"];
        fruits.forEach(function(item){
            document.write(item+"<br />");
        });
    </script>
</head>
<body>
    
</body>
</html>

Output

    apple
    mango
    banana
    guava

JavaScript Tutorial »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.