What is Control flow Statement.
Control flow statements in JavaScript manage the execution order of your code, allowing it to branch, repeat, or skip sections based on specific conditions. By default, the JavaScript interpreter executes scripts sequentially from top to bottom, one line at a time. Control structures break this linear path to make applications dynamic and interactive.
Branching means choosing one path from multiple possible paths based on a condition.
Repeating means executing the same block of code multiple times.
Skipping means not executing a section of code because a condition is not met.
Yesterday I have study about While Loop.
While Loop
A JavaScript while loop is a control flow statement that repeatedly executes a specified block of code as long as a test condition evaluates to true. Because it checks the condition before executing the loop's body, it is classified as an entry-controlled loop.
condition: An expression evaluated before each pass through the loop. If it evaluates to true, the code block runs. If it evaluates to false, JavaScript skips the loop entirely.
Syntax
while (condition) {
// code block to be executed
}
Example code
let count = 1;
while (count <= 3) {
console.log("Count is: " + count);
count++; // Updates the variable to eventually make the condition false
}
Output
Count is: 1
Count is: 2
Count is: 3
- Preventing Infinite Loops: You must alter a variable inside the loop body so that the condition eventually becomes false. Omitting count++ in the example above would lock the browser or application will be crash because of that infinite loops.
Flow chart
- This flowchart shows the working of the while loop in JavaScript. You can see the control flow in the while loop.
Example sum1
- Condition Satisfies (Loop Executes)
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
Execution:
1 <= 5 → true → print 1
2 <= 5 → true → print 2
3 <= 5 → true → print 3
4 <= 5 → true → print 4
5 <= 5 → true → print 5
6 <= 5 → false → stop
Output
1
2
3
4
5
Example sum2
- Condition Does Not Satisfy Initially (Loop Never Executes)
let i = 10;
while (i <= 5) {
console.log(i);
i++;
}
Execution:
10 <= 5 → false
the condition is false at the very beginning, the loop body is skipped completely.
Output
No output
Example sum3
- Condition Satisfies Once
let i = 5;
while (i <= 5) {
console.log(i);
i++;
}
Execution:
5 <= 5 → true → print 5
6 <= 5 → false → stop
Output
5
Reference
https://www.geeksforgeeks.org/javascript/javascript-while-loop/

Top comments (0)