Introduction to 'While' loops: To learn it, you gotta 'do' it. Infinite looping!


#1

So, I keep getting infinite loops, but I can't see why. I'm basically copying thhings that worked in the previous exercises and I can't work out what's wrong now!

The instructions read:
Your turn! Now that you've seen how do/while loops work, you can easily write your own. (Check the Hint if you need a syntax refresher!)
Your loop should print a string of your choice to the editor one time. Remember: make sure you give your while condition a way to become false, or it'll loop forever!

        Instructions

        Write a do/while loop inside the function we've created for you, getToDaChoppa. The function should log a string of your choice to the console. do it now!

Hint. Remember, the syntax looks like this:

            do {
            // The thing to do at least once!
            } while(  /* some condition */  );

The code I'm using is:

var myName = "Aname"

var getToDaChoppa = function(){
  do {
      console.log("My name is " + myName);
  } 
  while (myName === "Aname"){
     console.log("Get to the chopper!");
      myName = "Notaname";
  }
};

getToDaChoppa();

What am I doing wrong?! Please help! Thanks :smile:


#2

I noticed that line is missing a semi colon ; .. Hopefully that will help ?


#3

var myName = "Aname";

var getToDaChoppa = function(){
do {
console.log("My name is " + myName);
myName = "Notaname";
} while (myName === "Aname")
};
getToDaChoppa();


#4

The part that changes the myName var should be in the do portion otherwise consider it not a part of the loop @haxor789 could probly explain it better.


#5

Brilliant, thank you. That wasn't explained in the instructions! That's sorted it out now.


#6

A do-while loop is actually pretty similar to a regular while loop the main difference is that in a do while loop you first have the code and then the condition and in a while loop it's the other way around.

So its

do{} -> while(condition) -> do{} -> while(condition) -> ... stop

vs

while(condition) -> {} -> while(condition) -> ... -> stop

and as it is a loop as well you need to stop it after it's ready otherwise you create an infinite loop that freezes your browser. That's pretty much it. Here is a post about all kinds of loops if you have any more question on how to extend it feel free to ask: