Javascript Loops (for, while, do-while)
JavaScript loops allow you to execute a block of code multiple times. There are three types of loops in JavaScript:
- for loop
- while loop
- do-while loop
for loop:
A for loop is used to execute a block of code a specific number of times.
Syntax:
for (initialization; condition; increment) {
// code to be executed
}
- The initialization statement is executed one time only before the loop starts.
- The condition statement defines the condition for executing the loop.
- The increment statement is executed every time after the loop has been executed.
Example:
for (let i = 0; i < 5; i++) {
console.log(i);
}
Output:
0
1
2
3
4
while loop:
A while loop is used to execute a block of code as long as the condition is true.
Syntax:
while (condition) {
// code to be executed
}
Example:
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
Output:
0
1
2
3
4
do-while loop:
A do-while loop is used to execute a block of code at least once, and then repeatedly execute the block of code as long as the condition is true.
Syntax:
do {
// code to be executed
}
while (condition);
The condition statement defines the condition for executing the loop.
Example:
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
Output:
0
1
2
3
4
In all three loops, the break statement is used to exit the loop, and the continue statement is used to skip one iteration of the loop.