Baz Baz - 1 year ago 80
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

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

function f(areRowsSelectable){...}

Which of the following would you do?



Or something else?

Answer Source

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



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

Alternatively, also Boolean(v) would work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download