JavaScript : For Loop

In JavaScript, the for loop is used to iterate over a block of code multiple times. It's one of the most commonly used looping structures and provides a compact way to execute statements repeatedly. Here's the syntax of the for loop:

Syntax:


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

 

  • The initialization statement is executed before the loop starts. It's typically used to initialize a counter variable.
  • The condition is evaluated before each iteration. If it evaluates to true , the loop continues; if false , the loop terminates.
  • The increment/decrement statement is executed after each iteration. It's used to update the counter variable.
  • The code block inside the curly braces {} is executed for each iteration of the loop.

Example:


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

 

Output:


Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4

 

Infinite Loop:


If the condition of the for loop never evaluates to false, it will result in an infinite loop. Be cautious when writing for loops to avoid infinite loops.


// Infinite loop (condition always true)
for (;;) {
  console.log("This is an infinite loop");
}

 

Nested for Loop:


You can nest one or more for loops inside another for loop to create complex iteration patterns.


for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 2; j++) {
    console.log("i: " + i + ", j: " + j);
  }
}

 

Output:


i: 0, j: 0
i: 0, j: 1
i: 1, j: 0
i: 1, j: 1
i: 2, j: 0
i: 2, j: 1
 

The for loop is a versatile and powerful tool for iterating over arrays, generating sequences, and performing repetitive tasks in JavaScript. It's commonly used in various programming scenarios where you need to execute code multiple times.