What is the point of do...while statements

what is the point of do…while statements, for example:

const firstMessage = 'I will print!';
let i = 0

do {
 console.log(firstMessage)
 i++
} while (i < 4);

instead of that we could do:

const firstMessage = 'I will print!';
let i = 0

while (i < 4) {
  console.log(firstMessage)
}

it is much simpler

here is the link to the exercise:
https://www.codecademy.com/courses/introduction-to-javascript/lessons/loops/exercises/do-while-statement

The lesson states it: you get to perform the action once before evaluating the while conditions. It is an extra tool for specific situations. It has a long history in languages so it means people still find it useful to have that level of specificity.

It may seem trivial, but if you find yourself in certain situations you may find it useful too.
Check this discussion on stackoverflow for more nuanced takes on this: https://stackoverflow.com/questions/3003456/why-use-a-do-while-loop

1 Like

I’ve actually found do…while loops really useful in some of my personal projects. I don’t know if it’s the most efficient ways to do it, but I used them for when I wanted someone to answer a question (eg. a multiple choice question) with a specific input. So it runs the code once, asking the question, and will exit the loop once they have entered a valid input. I’ve found it to be very good for input validation but I’m sure there are other reasons for it’s use.

4 Likes

Probably just an oversight, but your ‘simpler’ code has an infinite loop.

1 Like

sorry about that, so it is basically used if your not sure how long is your while loop?

while loops are generally used when you’re not totally sure how long the loop will go on for. However a do while loop is guaranteed to run at least once. For example if you had

const firstMessage = 'I will print!';
let i = 4

while (i < 4) {
  console.log(firstMessage)
i++
}

Then it would not print out firstMessage, as the condition is checked before the content. however with a do while loop you would have

const firstMessage = 'I will print!';
let i = 4

do {
 console.log(firstMessage)
 i++
} while (i < 4);

And this would print firstMessage once to the console and then check the condition. This is why it is useful for things like questions with specific inputs, you want to ask the question at least once, and then only loop if the value returned is not what you wanted. With a while loop it’s entirely possible that the question could be skipped if the condition is not met, whereas regardless, a do while loop will print the question at least once.

4 Likes

thank you, now I get it

1 Like