Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit boolean conversion

Tags:

javascript

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?

like image 371
Baz Avatar asked Apr 29 '26 13:04

Baz


1 Answers

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.

like image 133
Christian Zosel Avatar answered May 01 '26 04:05

Christian Zosel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!