Skip to content
Advertisement

Using a function as statement in while loop JavaScript?

I believe similar questions have been posted before, but I don’t entirely understand why using a callback function as a While loop statement, such as seen below, results in an infinite loop:

do {
    console.log("repeat");
} while(myFunc);

function myFunc(){
    return false;
}

This version, on the other hand, prints “repeat” once and then stops:

do {
    console.log("repeat");
} while(myFunc === false);

Why is that?

Advertisement

Answer

myFunc is a variable (all functions in JS are object variables), and it’s not equal to false.

myFunc() on the other hand, is the results of myFunct being called, and is equal to false.

So you should compare the result of the function, not the function itself, by calling it:

do {
    console.log("repeat");
} while(myFunc() === false);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement