JavaScript - Loops

Javascript - loops repeat the piece code again and again till the condition is matched. Basically, loops automate the repetitive tasks within a program and it saves time & efficiency.

There are the followings javascript loops:

  • for loop
  • while loop
  • do…while loop
  • for/in loop

Javascript for Loop

Javascript for loop starts with the for keyword followed by a parenthesis and inside the parenthesis, Initialization, condition , and step values are inserted. For loop check the condition and if the condition is true then for loop continue the execution of Javascript code.

General Syntax
      for( initialization; condition; step value ){
    code block;
}
    
Try it now

Source Code

          
            for (i=1; i<=5; i++)  {  
 document.write(i + "<br/>"); 
}          
        
Try it now

Accessing Array Element Through For Loop

For loop is useful for iterating over an array. Let us take an example and understand it.

Source Code

          
            var appDevelopment = ["flutter", "ionic", "swift"];
for(var i=0; i<appDevelopment.length; i++) {
document.write(appDevelopment[i]);
document.write("</br>");
}          
        
Try it now

The for...in Loop

The for..in the loop is used to access the array element and also access the element of the object.

General Syntax
      for(variable in object) {
    // Code to be executed
}
    
Try it now

Source Code

          
            var fruits = {"mango": 50, "orange": 57, "grape":89 };
for(var fruit in fruits) {  
    document.write("<p>" + fruit + " = " + fruits[fruit] + "</p>"); 
}          
        
Try it now

The while loop

The while loop iterates the block of code until the condition is true. When while loop condition fails then the loop is stopped.

General Syntax
      while(condition) {
    // Code to be executed
}
    
Try it now

Source Code

          
            var i = 1;
while(i <= 5) {    
    document.write("<p>The number is " + i + "</p>");
    i++;
}          
        
Try it now

The do...while Loop

The do..while loop is a variant of the while loop. With do..while loop the block of code executes once and then check the condition. If the condition is true then the block of code will be executed again and again. If the condition fails then do....while loop stops the execution of the code.

General Syntax
      do {
    // Code to be executed
}
while(condition);
    
Try it now

Source Code

          
            var i = 1;
do {
  document.write("<p>The number is " + i + "</p>");
  i++;
} while (i <= 5);          
        
Try it now

Web Tutorials

Javascript Loops
Html Tutorial HTML
Javascript Tutorial JAVASCRIPT
Css Tutorial CSS
Bootstrap 5 Tutorial BOOTSTRAP 5
Bootstrap 4 Tutorial BOOTSTRAP 4