In this tutorial, you will learn how to use the JavaScript for loop statement to create a loop with various options.

Introduction to the JavaScript for loop statement

The JavaScript for loop statement allows you to create a loop with three optional expressions. The following illustrates the syntax of the for loop statement:

for (initialization; condition; post-expression) {
    // statements
}

1) initialization

The initialization expression initializes the loop. The initialization expression is executed only once when the loop starts. You typically use the initialization is to initialize a counter variable. If you use the var keyword to declare the counter variable, the variable will have either function or global scope. In other words, you can reference the counter variable after the loop ends. However, if you use the let keyword to declare the counter variable, the variable will have a blocked scope, which is only accessible inside the loop.

2) condition

The condition is an expression that is evaluated once before every iteration. The statement inside the loop is executed only when the condition evaluates to true. The loop is terminated if the condition evaluates to false. Note that the condition is optional. If you omit it, the for loop statement considers it as true.

3) post-expression

The for loop statement also evaluates the post-expression after each loop iteration. Generally, you use the post-expression to update the counter variable. The following flowchart illustrates the for loop:

JavaScript for Loop

In the for loop, the three expressions are optional. The following shows how to use the for loop without any expressions:

for ( ; ; ) {
   // statements
}

#javascript #programming #web-development #developer

JavaScript Control Flow - JavaScript for Loop
2.15 GEEK