javascript loops


Loops are higly useful in javascript to iterate some action over and over until some specified conditions are met. Instead of writing a huge block of code, we can use loop to make the javascript do the work. Two types of loops are supported in javascript which are as follows.

for Loop

for loop can be used when the number of iteration of a piece of code is known in advance.

Syntax

<script>
for (variable=startvalue; variable<=endvalue; variable=variable+incrementfactor){
  // script goes here
}
</script>

EXAMPLE

<script>
x = 0;
for (x = 1; x <= 5; x++) {
  document.write("The number is:"+ x +"<br>");
}
</script>

while Loop

while loop is used when the number of iteration is not known in advance so we write the script in such a way that the iteration continues until a defined condition is met.

SYNTAX

while (variable<=endvalue){
  // script goes here
} 

Example

<script>
x = 1; 
while(x <= 5) {
  document.write("The number is: "+ x +"<br>");
  x++;
}
</script>

BREAK & CONTINUE

break and continue are two special commands that can be used in a loop. break is used to break the iteration of the loop when certain condition is met. continue is used to break the iteration, perform some task and then continue the iteration again.

Example for Break

<script>
i = 1;
while (i <= 10){  
  if(i == 5){   
    document.write("FIVE <br>");
    break;
  } 
  document.write(i+"<br>");
  i++;
}
</script>

Example for Continue

<script>
i = 1;
while (i <= 10){  
  if(i == 5){   
    document.write("FIVE <br>");
    i++;
    continue;
  } 
  document.write(i+"<br>"");
  i++;
}
</script>