+ 1
JavaScript: why is it an infinite loop?
function isFalse() { return false; } while(isFalse) { continue; } If isFalse returns false, why does the loop execute? (It was a SL challenge question)
3 Answers
+ 10
The condition passed to while is a function and not the function call (which would have resulted in false)
Any function is evaluated as "truthy" so due to that fact the while loop goes on and on.
The correct syntax would be:
while(isFalse()) {
continue;
}
try this:
console.log(isFalse);
console.log(isFalse());
and you should see the difference right away
+ 4
`isFalse` doesn't call the function `isFalse` , `isFalse()` will do. //remember the parantheses.
function is a truthy value in javascript , if you convert it to boolean it'll be `true`.
Even a function with no statements is truthy:
```
Boolean(function(){}); //true
Boolean(()=>{}); //true
!!function(){} //true
!!()=>{} //true
```
more on this :
https://developer.mozilla.org/en-US/docs/Glossary/Truthy
+ 1
Burey š®š³Omkarš Thanks! It was tricky for me as a beginner in js :)