Loops

11 0 0
                                        

while loop Syntax:

while(condition){ //statements; }

As long as the condition is true, the loop will keep on iterating. Usually, a variable is used for incrementing or decrementing as the loop keeps on iterating until it meets the condition to be false.

=================

let x = prompt("Enter any number", 5);

function displayingSumOfX(){

     let sumOfX = 0;

     while(x > 0){

          sumOfX += Number(x);

          x--;

     }

     return sumOfX;

}

=================

HTML

document.write(displayingSumOfX())

Result:

15

Note: If you press ok and did not change the value in the input, the result is 15.


do - while loop syntax

do{ //statements; }while(condition);

This is just the same with the while loop, it is just that the do has the chance to execute even just once before it tested its condition. So, if the condition is true, it will keep on iterating but if it is false, at least it will execute even just once.

for loop syntax

for(initialization; condition; increment){ //statements; }

This works just like in the while loop but most of the things it needs for the loop is declared within the parenthesis.

==================

let x = Number(prompt("Enter any number", 5));

function displayingSumOfX(){

     let sumOfX = 0;

     for(let i=0; i <= x; i++){

          sumOfX += i;

     }

     return sumOfX;

}

==================

HTML

document.write(displayingSumOfX())

Result:

15

Note: In the while loop, I used decrementing while in the for loop I used the incrementing. Also, a loop that is incrementing does start counting with 0; So, if the condition is just less than, the result will just be 10. The reason why I used less than or equal is to include the 5 in the counting so that the result would be 15.


break - This is used to get out of the loop most especially if the loop is infinite.

==================

let x = Number(prompt("Enter any number", 100));

function displayingSumOfX(){

     let sumOfX = 0;

     let i = 0;

     while(i < x){

          if(i > 5){

               break;

          }

          sumOfX += i;

          i++;

     }

     return sumOfX;

}

==================

HTML

document.write(displayingSumOfX())

Result:

15


continue - this works like break but instead of getting out of the loop, it will just skip the iteration.

labelled break or labelled continue - the function is just the same but with a label. Like in break, it will get out of the loop until where that label is. Usually this is used in a nested loops.

==============

outer: for(initialize; condition; increment){

     for(initialize; condition; increment){

          if(condition){

              break outer;

          }

     }

}

==============

Javascript ProgrammingWhere stories live. Discover now