Member-only story
A for
loop in JavaScript is a loop statement that allows you to execute a block of code repeatedly for a fixed number of times. The for
loop consists of three parts: initialization, condition, and increment/decrement. Here's the basic syntax of a for
loop:
Not a Medium member? Read this article here
for (initialization; condition; increment/decrement) {
// code to be executed
}
- The initialization part initializes the loop counter and is executed only once at the beginning of the loop.
- The condition part specifies the condition for continuing the loop and is evaluated before each iteration of the loop. If the condition is true, the loop continues. If the condition is false, the loop terminates.
- The increment/decrement part updates the loop counter after each iteration of the loop.
Here’s an example of a for
loop that counts from 0 to 4:
for (let i = 0; i < 5; i++) {
console.log(i);
}
In this example, the initialization part sets the variable i
to 0, the condition part checks if i
is less than 5, and the increment part adds 1 to i
after each iteration of the loop. The loop will execute 5 times, with i
taking on the values of 0, 1, 2, 3, and 4, and each value of i
will be printed to the console.