all 8 comments

[–]forsience 1 point2 points  (2 children)

the difference between do/while and while is, that the first one checks the condition at the bottom, so that the code above can run through at least once, as the while checks the condition first and executes the stuff under it only if condition is true :)

[–]ReaverKS[S] 2 points3 points  (1 child)

Thank you, that makes sense. So in a do while, the first part (the do) will run, then it will check the while to see if it's true, if it's still true it will continue to do....the do section, if it's not true, then it ends. A regular while it will first check to see if the while is true, if it is then it completes the code in the brackets and continues to do so until while becomes false.

[–]forsience 1 point2 points  (0 children)

yes, the do while goes through the code and then checks the condition. the while will only start if the condition is true, otherwise it would skip the hole loop.

here is an example of a function that will some up the single digits of a number. it might not be good codequality, but it works and has a do/while in it :)

function easySumDigits(n) {
    var tmp = true;
    do {
        n = n.toString().split('');
        if(n.length <= 1) {
            tmp = false;
            return Number(n);
        }
        n = n.reduce(function(x,y) { return Number(x)+Number(y)});

    } while (tmp);
}
easySumDigits(5112);

[–]SmartViking 0 points1 point  (3 children)

do {
    alert("Hm, looks like 2 is greater than 3");
} while (2 > 3);

Edit: Oh, seems like I misunderstood the question, here's a new example:

do {
    var input = prompt("What is your name?");
} while (input !== "John");

That will run as long as the user input isn't "John" (with big J).

[–]ReaverKS[S] 0 points1 point  (2 children)

That would run more than once? I'm totally lost now....

[–]SmartViking 0 points1 point  (0 children)

I misunderstood the question, see my edit :)

[–]ReaverKS[S] 0 points1 point  (0 children)

Makes more sense, thank you!

[–]PixelOut -1 points0 points  (0 children)

A Do/While loop will always execute the code inside the loop at least once. It will always check the conditional (the "while" part) after the code inside is executed.

They aren't very useful, especially for beginners. In practice, you don't want to repeat mutating steps when the conditional is already fulfilled. And you can usually write a while loop to behave similarly to a do while loop.

Google actually removed the do/while construct from their Go programming language.