The do-while
loop in JavaScript is a control flow statement that executes a block of code at
least once and then repeats the execution as long as a specified condition is
true. It differs from the while loop in that the condition is evaluated after
the loop's body has been executed, ensuring that the code inside the loop runs
at least once, regardless of the condition.
Syntax
do { // Code to be executed } while (condition);
How It Works
· Execution Starts: The code block inside the do section is executed first.
· Condition Check: After executing the code block, the condition in the while statement is evaluated.
1. If the condition is true, the loop starts over and the code block is executed again.
2. If the condition is false, the loop terminates, and the program continues with the next statement after the loop.
Example 1: Print numbers from 0 to 4
printNumbers.js
let count = 0; do { console.log(`Count is: ${count}`); count++; } while (count < 5);
Output
Count is: 0 Count is: 1 Count is: 2 Count is: 3 Count is: 4
· The loop starts by printing Count is: 0.
· count is then incremented by 1.
· The condition count < 5 is checked.
· Since count is now 1 (which is less than 5), the loop runs again.
· This continues until count reaches 5, at which point the condition becomes false and the loop terminates.
Example 2: do-while Loop Executing at Least Once even though condition evaluates to false.
executeAtleastOnce.js
let number = 10; do { console.log("This will print once even if the condition is false."); } while (number < 5);
Output
This will print once even if the condition is false.
· The condition number < 5 is false from the start (number is 10).
· However, because of the do-while structure, the message inside the loop is printed once before the condition is even checked.
The do-while loop is guaranteed to execute the block of code at least once because the condition is evaluated after the code block is executed. It's particularly useful when you need to run some code at least once before checking a condition, such as when validating user input.
No comments:
Post a Comment