In JavaScript, the for loop is a common way to execute a block of code multiple times. It’s typically used when you know the number of iterations you need to perform ahead of time.
Here’s the basic syntax of a for loop:
for (initialization; condition; increment/decrement) {
// code to be executed
}
The initialization statement is executed before the loop starts and is used to initialize a counter variable. The condition statement is evaluated at the beginning of each iteration and determines whether the loop should continue. The increment/decrement statement is executed at the end of each iteration and is used to modify the counter variable.
Here’s an example of a for loop that iterates through the numbers 0 to 4 and logs each number to the console:
for (let i = 0; i < 5; i++) {
console.log(i);
}
In this example, the initialization statement initializes the counter variable i to 0. The condition statement checks whether i is less than 5. The increment statement increments i by 1 at the end of each iteration.
You can also use the break statement inside a for loop to exit the loop early if a certain condition is met. For example:
for (let i = 0; i < 5; i++) {
if (i === 3) {
break;
}
console.log(i);
}
In this example, the for loop iterates through the numbers 0 to 4. However, if the value of i is 3, the break statement is executed, causing the loop to exit early.
You can also use the continue statement inside a for loop to skip over certain iterations based on a condition. For example:
for (let i = 0; i < 5; i++) {
if (i === 3) {
break;
}
console.log(i);
}
In this example, the for loop iterates through the numbers 0 to 4, but if the value of i is 3, the continue statement is executed, causing that iteration to be skipped over.
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.