0

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?

The Dembinski
  • 1,469
  • 1
  • 15
  • 24
  • 2
    Why is there a reason at all to convert something to a boolean in an `if` condition? `if(something)` is perfectly sufficient. – Sebastian Simon Oct 19 '16 at 23:49
  • "Better" is a matter of opinion. There are some specific uses where the function is *convenient*, but that's another matter. –  Oct 19 '16 at 23:50
  • @Xufox - Just to confirm, you're saying there's never a time where it could be appropriate to use `!!something`? – The Dembinski Oct 19 '16 at 23:51
  • @TheDembinski It’s not about whether it’s appropriate or not, it’s just not necessary. I’m just saying it’s not necassary in `if` conditions. If you ever actually need a boolean value, you can use `!!`. – Sebastian Simon Oct 19 '16 at 23:54
  • @Lucero definitely a duplicate. Flagging for removal – The Dembinski Oct 19 '16 at 23:56

2 Answers2

0

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.

Kaan
  • 86
  • 4
0

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).

William Martins
  • 1,969
  • 1
  • 18
  • 22