android-logo

JavaScript Loop


In JavaScript, loops are used to conduct repetitive activities based on a condition.

In JavaScript, there are four different forms of loops.

  • for loop
  • while loop
  • do-while loop
  • for-in loop

for loop

For loops are typically used to repeat code for a certain number of times.

Syntax


for (initialization; condition; finalExpression) {
    // code block
  } 

Lets take an example and iterate through integers from 1-5


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

Output

1
2
3
4
5


while loop

The while loop iterates across a block of code as long as a condition is met.

Syntax


while (condition)  
{  
  // code block  
}  

Lets take an example and iterate through integers from 1-5


let i = 1;
while (i <= 5) {
 document.write(i + "<br/>")  
  i++;
}

Output

1
2
3
4
5


do-while loop

Whether the condition is true or not, the do while loop script is executed at least once.

Syntax


do{  
    // code block
} while (condition);  


Lets take an example and iterate through integers from 1-5


var i=1;  
do{  
document.write(i + "<br/>");  
i++;  
}while (i<=5);  

Output

1
2
3
4
5


for-in loop

The JavaScript for in statement iterates across an Objects properties.

Syntax


for (key in object) {
    // code block 
  }


Lets take an example and iterate through Objects properties.


const employee = {emiId:"101", empTitle:"Developer", age:36}; 

let result = "";
for (let val in employee) {
  result += employee[val] + " ";
}

Output

101 Developer 36


previous-button
next-button

facebook-logo
twitter-logo
instagram-logo

2020 © All rights reserved.