
JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while of for-in loops. It makes the code compact and mostly used in arrays.
Following are the different types of loops in JavaScript
1. for loop
2. while loop and
3. do-while loop
1. JavaScript For Loop
The JavaScript for loop iterates the elements for the fixed numbers of times. It should be used if the number of iteration is known.
Following is the syntax
for (initialization; condition; increment)
{
code to be executed here
}
For example
for (i = 1; i<=5; i ++) { console.log(i + "<br/>") } // output 1 2 3 4 5
2. JavaScript While loop
The JavaScript while loop iterates the elements for the infinite numbers of times. It should be used if the number of iteration is not known.
The syntax of while loop is
while (condition)
{
code to be executed here
}
For example
var i=10; while(i <=15) { console.log(i); i++; } //output 10 11 12 13 14 15
3. JavaScript Do While Loop
The do while loop is the variant of the while loop. This loop will execute the code block once, before the checking the if condition is true, then it will repeat the loop as long as the condition is true.
The syntax of do while loop is
do{ //code to be executed here } while(condition);
Following is the example
let num = " "; let i = 0; do { num += " Number : " + i; i++; } while(i < 10); console.log(num);