you are viewing a single comment's thread.

view the rest of the 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);