Recently started my journey with JS ( again… this time learning React JS ) . Came across this IF condition which defied all logical explanations ( to me at least )
var flag = true;
if(flag && "Flag is true")
{
//console.log("\n Prints Flag is True, Strange !!");
}
The above code snippet printed “Flag is true “. This lead to a journey to understand Truthy and Falsy in Javascript :).
The explanation : JS evaluates the last expression and if true return the expression.
string if empty is false , return false string if !empty is true , return string
I ran a small experiment using chrome console for the same
| Code snippet | Result |
|---|---|
| if(true && “string”) {console.log(“TRUE”)} else console.log(“FALSE”); | TRUE |
| if(true && “”) {console.log(“TRUE”)} else console.log(“FALSE”); | FALSE |
| if(true && 1) {console.log(“TRUE”)} else console.log(“FALSE”); | TRUE |
| if(true && 0) {console.log(“TRUE”)} else console.log(“FALSE”); | FALSE |
More examples of whats Truthy and Falsy
