For Loop in JavaScript

A for loop in JavaScript repeatedly executes a block of code as long as a specified condition is true. It includes initialization, condition checking, and iteration steps, making it efficient for controlled, repetitive tasks.

Syntax:

for (statement 1 ; statement 2 ; statement 3){
    code here...
}
  • Statement 1: It is the initialization of the counter. It is executed once before the execution of the code block.
  • Statement 2: It defines the testing condition for executing the code block
  • Statement 3: It is the increment or decrement of the counter & executed (every time) after the code block has been executed.

Example:

javascript
// JavaScript program to illustrate for loop
let x;

// for loop begins when x=2
// and runs till x <=4
for (x = 2; x <= 4; x++) {
    console.log("Value of x:" + x);
}

Output:

Value of x:2
Value of x:3
Value of x:4

JavaScript For Loop

JavaScript for loop is a control flow statement that allows code to be executed repeatedly based on a condition. It consists of three parts: initialization, condition, and increment/decrement. This loop iterates over a code block until the specified condition is false.

Similar Reads

For Loop in JavaScript

A for loop in JavaScript repeatedly executes a block of code as long as a specified condition is true. It includes initialization, condition checking, and iteration steps, making it efficient for controlled, repetitive tasks....

Flow chart

This flowchart shows the working of the for loop in JavaScript. You can see the control flow in the For loop....

Statement 1: Initializing Counter Variable

Statement 1 is used to initialize the counter variable. A counter variable is used to keep track of the number of iterations in the loop. You can initialize multiple counter variables in statement 1....

Statement 2: Testing Condition

This statement checks the boolean value of the testing condition. If the testing condition is true, the for loop will execute further, otherwise loop will end and the code outside the loop will be executed. It is executed every time the for loop runs before the loop enters its body....

Statement 3: Updating Counter Variable

It is a controlled statement that controls the increment/decrement of the counter variable....

More Loops in JavaScript

JavaScript has different kinds of loops in Java. Some of the loops are:...