Analyze the following code:
let a = 10; do { console.log(a--); } while (a > 3);
Which statement can replace the do ... while
from the example above?
-
while (a > 4) console.log(--a);
-
while (a > 2) console.log(--a);
-
while (a > 3) console.log(a--);
-
while (a >= 3) console.log(a--);
Explanation & Hint:
The while loop has the same condition as the do…while loop, a > 3. The loop will continue executing as long as the condition is true. The code inside the loop is the same: console.log(a–), which displays the value of a and then decrements it by 1. The difference between do…while and while loops is that a do…while loop executes the code block at least once, even if the condition is initially false. In contrast, a while loop checks the condition first and only executes the code block if the condition is true. Since the do…while loop in the given code will always execute at least once (as a starts with a value greater than 3), it can be replaced with a while loop without affecting the output. |