Javascript Tutorial
Javascript Tutorial Introduction to Javascript JavaScript Code Editors & IDE JavaScript Hello World Example Javascript Syntax and Rules syntax_rules javascript_identifiers JavaScript Keywords & Reserved Words javascript_variables JavaScript Const JavaScript let vs var vs const Data Types in JavaScript JavaScript String Template Literals & String interpolation in JavaScript Tagged Templates in JavaScript String to Number in JavaScript Number Data Type in JavaScript NaN in JavaScript JavaScript Number Min & Max & Safe Values JavaScript EPSILON & Floating point precision Infinity in JavaScript JavaScript Bigint BigInt Vs Number in JavaScript Boolean Data Type in JavaScript Undefined in JavaScript Null in JavaScript Null vs Undefined in JavaScript JavaScript Operators Arithmetic Operators in JavaScript Unary plus & minus operators in JavaScript Increment & Decrement Operators in JavaScript Comparison or Relational operators in JavaScript Strict Equality (==) Loose Equality (===) in JavaScript Ternary Conditional Operator in JavaScript Logical Operators in JavaScript Bitwise Operators in JavaScript Assignment Operators in JavaScript Nullish Coalescing Operator in JavaScript Comma Operator in JavaScript Typeof JavaScript Operator Precedence in JavaScript JavaScript if, else & nested if statement Switch Statement in JavaScript While & Do While Loops in JavaScript For Loop in JavaScript Break statement in JavaScript Continue Statement in JavaScript Arrays in JavaScript Array Constructor in Javascript Sparse Array Vs Dense Array in JavaScript How to merge Arrays in JavaScript Array Methods in JavaScript Functions in JavaScript Function Parameters & Arguments in JavaScript JavaScript Default Parameters Pass by Value and Pass by Reference in Javascript Function Expression in Javascript Nested Functions in JavaScript Immediately-invoked Function Expressions (IIFE) JavaScript Callback Functions Arrow Functions in JavaScript Arguments Object In JavaScript Rest Parameters in JavaScript Objects in Javascript Create Objects in JavaScript JavaScript Object Properties Computed Property Names in JavaScript Object Literal in JavaScript Constructor Function & New Operator in JavaScript Delete Operator in JavaScript hasOwnProperty in JavaScript Using Getters and Setters in Javascript DefineProperty in JavaScript JavaScript Property Descriptors Enumerable, Writable & Configurable Object Destructuring in JavaScript Variable Scope in JavaScript Hoisting in JavaScript Lexical Scope & Closures in JavaScript This in JavaScript Global Object, Window & Globalthis in JavaScript Call function in Javascript Prototype In Javascript Prototype Inheritance in JavaScript Instanceof Operator in JavaScript Spread Operator in JavaScript

For Loop in JavaScript

JavaScript for loop repeats a group of statements until a specified condition evaluates to false. The for loop allows us to initialization expression, condition,specify an and final expression as part of the loop syntax.

For Loop

The syntax of the for loop is as below.

It starts with for keyword followed by three optional expressions inside parentheses separated by semi-colons. Finally, a block of statements inside curly braces follows them. These block statements execute for each iteration of the loop.

Example

                            
for ([initial-expression]; [condition]; [final-expression])
{ statements }
   
  
                        
                            
                        

The three optional expressions are

  1. Initial-expression
  2. Condition
  3. Final-expression

Initial Expression

The initial-expression is the expression, that JavaScript executes at the beginning of the loop. It runs only once.

  1. Initial-expression is optional
  2. You can execute any expression here including complex expressions.
  3. The main purpose of it to initialize the loop counters using assignment expressions
  4. You can also declare variables here using var & let.
  5. Variables declared with let are local to the statement.
  6. Variables declared with var are not local to the loop, You can access them outside the loop also
  7. The result of this expression is discarded.

Condition

The condition is evaluated before the beginning of each iteration of the loop. If the condition returns true, then it executes the block of statements. If returns false the loop terminates.

condition is optional. An empty condition returns true.

Final Expression

For Loop executes the final expression at the end of each iteration of the loop and before the next evaluation of the condition

The main purpose of it is to increment or update the loop counter.

Statements

A statement that is executed as long as the condition evaluates to true.

Use the block { ... } to group the multiple statements together. For a single statement, no need to use { ... }

You can also use an empty statement just by adding ;

How it works

When a For loop executes, the following occurs

  1. Executes the initial-expression. This runs only once
  2. Evaluates the condition. If the value is True then continue to step 3. If false the loop terminates.
  3. Executes the statements.
  4. Executes the final-expression.
  5. Control returns to Step 2.

For Loop Example

Example

                            
for (let i = 0; i < 5; i++) {
  console.log(i);
}
console.log("End of Loop");
 
 
*** Console ***
0
1
2
3
4
End of Loop
 
 
                            
                        
                            
                        
  1. The expression let i = 0 is the initial-expression and runs only once. It initializes the loop local variable i with a value of 0
  2. i < 5 is the condition, which returns true as long as the i is less than 5. Hence the loop continues. If it returns false, the loop terminates.
  3. The loop runs for the first time and statements inside the { } executes.
  4. he final-expression i++ executes. Which increments the value of i by 1
  5. Now, the control returns to step 2

let is local to the for loop

In the example above we used the let to declare the loop variable i. Hence its scope is local to the loop body. Trying to use outside the loop will result in the error Error: i is not defined.

Example

                            
for (let i = 0; i < 5; i++) {
  console.log(i);
}
 
console.log(i); //i is not defined  
                        
                            
                        

var is available outside the for loop.

We can also use var to declare the variable, in that case, you can use the variable outside the For loop.

Example

                            
for (var i = 0; i < 5; i++) {
  console.log(i);
}
 
console.log(i); //5  
                        
                            
                        

Initial expression is optional

We can also initialize the initial value outside the for loop and keep the initial-expression empty

Example

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

Condition is also optional

The condition is also optional, But an empty condition is treated as True. Hence this will create an infinite loop

Example

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

Use Break statement to break out of the loop

You can use the break statement to break out of a For loop.

Example

        
let i = 0;
for (; ; i++) {
  if (i >= 5) break;
  console.log(i);
}
  
    
        
    

Final Expression is also optional

In the following example Initial Expression, condition & final expression is empty.

We initialize the value of the counter before entering the loop. Check the condition in the loop body. Also, execute the Final expression as the last statement of the loop.

Example

        
let i = 0;
for (;;) {
  if (i >= 5) break;
  console.log(i);
  i++;
}
  
    
        
    

The above is equivalent to the following code.

Example

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

Skipping an Iteration

Use the continue statement to skip the rest of the for loop and move over to the next iteration. The following example, will not print the 0 & 1.

Example

        
let i = 0;
for (let i = 0; i < 5; i++) {
  if (i < 2) continue;
  console.log(i);
}
 
** Output **
 
2
3
4
  
    
        
    

Loop Backwards

You can also go backward. Start the count from 5 and decrement in each iteration.

Example


let i = 0;
for (let i = 5; i > 0; i--) {
  console.log(i);
}
 
*** Console **
5
4
3
2
1



Complex Expressions

We can also include complex expressions in Initial & final expressions

Example

 
for (let i = 0, j = 0; i < 5; i = j + 1, j++, i++) {
  console.log(i + j);
}



Statement body is also optional

In the following code, we do not have for the body.

Example

 
let sum = 0;
 
for (let i = 0; i <= 5; sum = sum + i, i++);
 
console.log(sum);



For Loop More Examples

Example

        
let persons = new Array("John", "Ann", "Aaron", "Edwin", "Elizabeth");
for (let i=0; i < persons.length;i++)
{
  console.log(persons[i]);
}