JavaScript: why is it an infinite loop? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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)

23rd Feb 2020, 1:08 PM
Prof. Dr. Zoltán Vass
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
23rd Feb 2020, 1:14 PM
Burey
Burey - avatar
+ 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
23rd Feb 2020, 1:15 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 1
Burey 🇮🇳Omkar🕉 Thanks! It was tricky for me as a beginner in js :)
23rd Feb 2020, 1:16 PM
Prof. Dr. Zoltán Vass