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.
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.
Now let's understand this with the help of an example
// for loop begins when x=2
// and runs till x <= 4
for (let x = 2; x <= 4; x++) {
console.log("Value of x:" + x);
}
Output
Value of x:2 Value of x:3 Value of x:4
For loop to print table of a number.
let x = 5
for (let i = 1; i <= 10; i++) {
console.log(x * i);
}
Output
5 10 15 20 25 30 35 40 45 50
For loop to print elements of an array.
let arr = [10, 20, 30, 40];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Output
10 20 30 40
Flow chart
This flowchart shows the working of the for loop in JavaScript. You can see the control flow in the For loop.