In JavaScript, you can use loops to repeat a block of code multiple times. There are two types of loops you can use: for
loop and while
loop. Here is how you can create and use them:
for
loop:
The for
loop is used when you know the number of iterations in advance.
Syntax:
for (initialization; condition; iteration) {
// code to be repeated
}
Example:
for (let i = 0; i < 5; i++) {
console.log(i);
}
Output:
0
1
2
3
4
while
loop:
The while
loop is used when the number of iterations is not known in advance.
Syntax:
while (condition) {
// code to be repeated
}
Example:
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
Output:
0
1
2
3
4
In both loop types, you can manipulate the loop variable inside the loop body to control the program flow. Make sure to include a way to exit the loop to prevent infinite looping.