Simply put - I use if(!!something)
frequently while totally aware of Boolean(something)
but have never use it for reasons that I can't justify.
Are there any reasons to use one over the other?
Simply put - I use if(!!something)
frequently while totally aware of Boolean(something)
but have never use it for reasons that I can't justify.
Are there any reasons to use one over the other?
Both have the same result. You could also use just
if(something){
// do something
}
the only difference could be performance issues but I am not sure which way would be better.
Both evaluate to true
or false
based in the same rules:
The value passed as the first parameter is converted to a boolean value, if necessary. If value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false. All other values, including any object or the string "false", create an object with an initial value of true.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean#Description
There is also this handy table to check those values:
https://dorey.github.io/JavaScript-Equality-Table/
I think that the usage depends on you/your team. Because some newcomers to javascript may find out that "!!
" is kinda strange and "hacky" and "Boolean(value)
" seems to be more clear.
Also, when using with if
, you don't need to "convert to boolean" (using !!
). You can just use the if(value)
and value will be converted to truthy or falsy values (as showed in the table that I linked above).