'falsy' values in JavaScript
All values when passed to Boolean()
returns false are 'falsy' values.
The below are the finite set which is considered as 'falsy' values in JavaScript. All others are considered as 'truthy'. It's like vowels and consonants in English alphabets.
false
0
'' or `` or ""
0n //BigInt
undefined
null
NaN
It's very easy to filter the above 'falsy' values in a variable,
let a = false;
if (a) {
//does not enter
}
or
if (Boolean(a)) {
//does not enter
}
But one has to be careful when dealing with 0
, false
, or null
as users may genuinely what to input those values to your API or DB etc.
The below method ignores 0
, false
, and null
but only check for empty strings, undefined, NaN and empty object values. If you find it useful, please feel free to use it.
You can replace typeof value === 'string'
and isNaN(value)
with more reliable checking. Links below.