JavaScript – Loops

Loop control statements:

  • Loop control statements execute a block of instructions repeatedly as long as the condition is valid.
  • Loops classified into
    • For loop – we use for loop when we know the number of iterations
      • Print 1 – 10 numbers
      • Print all elements of Array
  • While Loop – we use when we don’t know the number of iterations
    • Print file text – we don’t know how many lines are present
    • Print Database table details – we don’t know how many records are present
  • Do-While Loop – When we want to execute loop at least once. Execute the Block and the check the condition from the next iteration.

Program to print numbers from 1 to 10 and 10 to 1:

<html>
            <head>
                        <script>
                                    function print1to10(){
                                                for(var i=1 ; i<=10 ; i++){
                                                            document.write(“i val : ” + i + “<br/>”);
                                                }
                                    }
                                    function print10to1(){
                                                for(var i=10 ; i>=1 ; i–){
                                                            document.write(“i val : ” + i + “<br/>”);
                                                }
                                    }
                        </script>
            </head>
            <body>
                        <button onclick=”print1to10()”> Print 1 to 10 </button>
                        <button onclick=”print10to1()”> Print 10 to 1 </button>
            </body>
</html>
Scroll to Top