In JavaScript, the for loop is used to iterate over a block of code multiple times. It's one of the most commonly used looping structures and provides a compact way to execute statements repeatedly. Here's the syntax of the for loop:
for (initialization; condition; increment/decrement) {
// Code block to be executed
}
for (let i = 0; i < 5; i++) {
console.log("Iteration " + i);
}
Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
If the condition of the for loop never evaluates to false, it will result in an infinite loop. Be cautious when writing for loops to avoid infinite loops.
// Infinite loop (condition always true)
for (;;) {
console.log("This is an infinite loop");
}
You can nest one or more for loops inside another for loop to create complex iteration patterns.
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 2; j++) {
console.log("i: " + i + ", j: " + j);
}
}
i: 0, j: 0
i: 0, j: 1
i: 1, j: 0
i: 1, j: 1
i: 2, j: 0
i: 2, j: 1
The for loop is a versatile and powerful tool for iterating over arrays, generating sequences, and performing repetitive tasks in JavaScript. It's commonly used in various programming scenarios where you need to execute code multiple times.