For Loop
In JavaScript, a for loop is a control structure used to repeat a block of code a specific number of times based on a condition. It consolidates variable initialization, condition evaluation, and a final update expression into a single, highly readable statement.
For Loop Syntax
- The standard loop statement accepts three optional expressions separated by semicolons:
for (initialization; condition; afterthought) {
// Code to execute on every iteration
}
Initialization: Evaluates once before the loop begins. It typically declares a local loop counter using let.
Condition: Evaluated before every iteration. If it evaluates to true, the code block runs; if false, the loop exits.
Afterthought: Evaluates at the very end of every loop iteration, right before re-checking the condition. It is generally used to increment or decrement the counter.
Example Code
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
Flow chart
- This flowchart shows the working of the for loop in JavaScript. You can see the control flow in the For loop.
do while loop
The do...while statement creates a loop that executes a specified block of code at least once, and then repeats the execution as long as a test condition evaluates to true.
- Because the condition is checked at the end of each iteration instead of the beginning, it is classified as an exit-controlled loop.
Syntax
do {
// Code block to be executed
} while (condition);
- Exit Controlled Loops: In this type of loop the test condition is tested or evaluated at the end of the loop body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false. the do-while loop is exit controlled loop.
Example sum1
- Condition is True (Loop Repeats)
let i = 1;
do {
console.log(i);
i++;
} while(i <= 5);
Output
1
2
3
4
5
Explanation:
i = 1 → prints 1
Condition 1 <= 5 → true
Repeats until i becomes 6
Example sum2
- Condition is False Initially
let i = 10;
do {
console.log(i);
} while(i < 5);
Output
10
Explanation:
The code inside do runs first.
Then condition 10 < 5 is checked.
Condition is false, so loop stops.
Output is printed once.
A while loop checks the condition before executing the loop body, so it may execute zero times. A do...while loop executes the loop body first and checks the condition afterward, so it always executes at least once.
References
https://www.geeksforgeeks.org/javascript/javascript-for-loop/
https://www.geeksforgeeks.org/javascript/javascript-do-while-loop/

Top comments (0)