• Post author:
  • Post category:Blog
  • Reading time:2 mins read
  • Post last modified:June 12, 2024

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.

For more Questions and Answers:

JavaScipt Essentials 1 (JSE) | JSE1 – Module 4 Test Exam Answers Full 100%

Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments