JavaScript for loop

The for loop in JavaScript is used to run a piece of code a certain number of times. The basic syntax is as follows:

for (initialization; condition; increment/decrement) { // code to be executed }

The initialization statement is executed once before the loop begins, and is typically used to initialize a loop counter variable. The condition is an expression that is evaluated at the beginning of each iteration of the loop, and if it is true, the code inside the loop block is executed. Once the code inside the loop block is finished executing, the increment/decrement statement is executed, and the condition is evaluated again. This process repeats until the condition is no longer true.

This is an example of the For-Loop statement:

for (let i = 0; i < 10; i++) { console.log(i); }

In this example, the for loop executes 10 times. The initialization statement sets the loop counter variable i to 0. The condition checks whether i is less than 10, and if it is, the loop block is executed. During each iteration of the loop, the current value of i is printed to the console using console.log(), and then i is incremented by 1 using the ++ operator. The loop will repeat until i reaches 10, at which point the condition will no longer be true, and the loop will terminate.

Note that like the while loop, if the condition is never false, the for loop will continue to execute indefinitely, resulting in an infinite loop. It's important to ensure that the condition will eventually become false in order to prevent this from happening.

Last updated