Do/while Loops: To Learn it you gotta 'do' it... infinite loop?


#1



So... this was my original code and it worked just fine:

var getToDaChoppa = function(){
do {
console.log("Don't get too close!");
}while(getToDaChoppa===true);
};

getToDaChoppa(false);

However, then I went back and remembered that in while loops, writing (getToDaChoppa===true) is the exact same thing as writing (getToDaChoppa)

*a principle taught earlier when it talked about brevity being the key to programming

However, when I replaced that and changed my code to this:

var getToDaChoppa = function(){
do {
console.log("Don't get too close!");
}while(getToDaChoppa);
};

getToDaChoppa(false);

(bolded is the changed portion)

The browser kept crashing so I'm assuming it ran an infinite loop. Can someone explain why this is? Did I misunderstand the principle?

Thank you in advance!


#2

getToDaChoppa is the function? i don't see why you would use that as condition for the while loop. anyway, functions are evaluate to true, which you can simply see here:

if (getToDaChoppa){
   console.log(true);
}

this raises the question, why is this false then:

while(getToDaChoppa===true);

well, a function on its own might be true, but it doesn't equal true.

if you where to use false:

while(false);

it works fine. You pass false as argument on function call:

getToDaChoppa(false);

if where to add a function parameter:

var getToDaChoppa = function(x){

and use the parameter (which contains the argument), everything works fine:

while(x);

i honestly don't see, why you would use a function as a condition for a while loop


#3

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