Truthy and Falsy
Deepankar Bhade /
1 min read--
Each value in javascript has a Boolean value associated with it we can try to understand it with this example.
index.js
let x; if(x){ console.log('True runs') }else{ console.log('False runs') } // OUTPUT: // "False runs"
The false statement runs but why does this happen? This is where truthy & falsy come into action.
All values in javascript when used in a Boolean context inherit a boolean value. In the above example, the variable x was undefined and is considered false when encountered in a Boolean context hence falsy.
Values that are considered falsy in javascript
false0,-00n"",''(empty string)nullundefinedNaNdocument.all
Every value that is not falsy is truthy:
index.js
let x = 10; if(x){ console.log('True runs') }else{ console.log('False runs') } // OUTPUT: // "True runs"
Here x does not come under any falsy value therefore is truthy.