4

Is there any difference (in JS) between using the double negative !! and not using it at all?

For example

if (!!variable){... vs. if (variable){...

I know there are times where I've gotten a warning using the 2nd method..

When should each be used? and when will each throw a warning in the console? (for variables, objects, arrays etc.)

Thanks!!

d-_-b
  • 21,536
  • 40
  • 150
  • 256
  • 3
    http://stackoverflow.com/questions/4686583/can-someone-explain-this-double-negative-trick basically it converts it into a boolean value. – Smern Apr 05 '13 at 23:52
  • 1
    This is, in fact, a different question. Just because some *answers* to the other question happen to answer this one doesn't make them actually the same. – SamB May 16 '19 at 01:03

2 Answers2

3

There is a difference for assigning it, but not for using it in a conditional statement. The reason the !! is used is because the first ! will convert your variable to its truthy evaluation and then not it. So "hello" becomes true, is then negated, becomes false, and the second ! will negate the false, resulting in true. This can be desirable when trying to obtain the thruthy value from a variable. However, there is not much gained by doing it in an if statement.

Travis J
  • 81,153
  • 41
  • 202
  • 273
  • 1
    awesome thanks! "`when trying to obtain the thruthy value`" is a great way to explain this. thanks! I see this used when checking for existence of things other than variables so that makes sense. – d-_-b Apr 05 '13 at 23:56
3

In this particular case, there is no difference. In fact, !!variable is wasteful.

However in more general cases, it casts the variable to a boolean. Personally I've only found this useful when debugging, and to learn what values are truthy and falsy.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592