Baz Baz - 26 days ago 5
Javascript Question

Explicit boolean conversion

I have a variable which is either set to something or is undefined. I wish to pass to a function

true
if the variable is defined else
false
. Here is the function:

function f(areRowsSelectable){...}


Which of the following would you do?

f(v);


f(v?true:false);


Or something else?

Answer

I usually use double negation (which means applying the logical NOT operator twice) for explicit boolean conversion:

!!v

Examples:

!!'test' // true
!!'' // false
!!0 // false
!!1 // true
!!null // false
!!undefined // false
!!NaN // false

Alternatively, also Boolean(v) would work.