10. do / while not working as expected


10. To learn it, you gotta Do it

When running this code, it prints both statements. I thought it would only run the do-statement because loopy is not true? If loopy IS true the browser crashes. I feel like it's doing the opposite of what it should?

var getToDaChoppa = function(){
  // Write your do/while loop here!
  var loopy = false;
  do {
      console.log("If it bleeds we can kill it");
  } while (loopy) {
      console.log("Get to da choppa!");
      loopy = false;



for (var i = 0; ... ) {


while (condition) {


do {

} while (condition);

Note the difference in the two while loops.


I want it to log "Get to da choppa!" when loopy is true and then make loopy false and not run again.


I think my problem is that I don't understand the difference?


A while loop will only run if the condition is met, initially. A do-while loop will execute at least once, before testing the condition. It is a subtle difference, to be sure.


See, that's what I thought I understood, but clearly I am not because then it doesn't make sense to me that my code is acting the way it does. Why does it log both statements to the console when the condition is not met? And why, if loopy is true, does it crash the browser when I tell it to change loopy to false afterwards?


In your do-while example the code block after the while is a stand alone segment that executes freely.

Try it:

{ console.log("This code block will execute unconditionally."); }

The do-while loop places the executable code before the conditional.


Ahaa ... I think I've completely misunderstood how these things work. Thanks for explaining! I think I get it now.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.