Javascript do while loop
Created By: chatGPT
JavaScript's
do...while
loop allows you to execute a block of code at least once before checking a condition. This is useful when you want to ensure the code runs before validating any conditions. The syntax is simple and looks like this:do {
// Code to be executed
} while (condition);
In this structure, the code block inside the
do
will execute, and then the while
condition will be evaluated. If the condition is true
, the loop will continue; if false
, the loop will end.let count = 0;
do {
console.log('Count is: ' + count);
count++;
} while (count < 5);
In the above example, the output will be:
- Count is: 0
- Count is: 1
- Count is: 2
- Count is: 3
- Count is: 4
This shows that the loop executed 5 times before stopping once count
reached 5.
let i = 10;
do {
console.log(i);
i--;
} while (i > 0);
This will output the numbers from 10 down to 1, demonstrating how the
do...while
loop continues to execute as long as the condition remains true. Importantly, the loop ensures that the code runs at least once, even if the condition is initially false.let answer;
do {
answer = prompt('Do you want to continue? (yes/no)');
} while (answer !== 'no');
In this example, the loop prompts the user to continue until they respond with 'no'. This is a practical use case of a
do...while
loop in a real application where at least one interaction is needed.// Note: The prompt function may not work in certain environments without a browser.