0

What is the difference between the below codes in JavaScript?

if(x)
 doSomething();

and

if(!!x)
 doSomething();
Hamed Hajiloo
  • 964
  • 1
  • 10
  • 31
  • This is a weird thing to do in an `if`, but totally normal to use elsewhere to force a boolean like `let y = !!x`. – tadman May 09 '23 at 16:33
  • 1
    There is no difference at all, because the way the expression in an `if` test is evaluated is exactly the same as what `!!x` means. – Pointy May 09 '23 at 16:33
  • 1
    Outside of an `if` test, of course, there is a difference: `!!` converts any value to a boolean value according to the standard interpretation of expressions in contexts like an `if` test. – Pointy May 09 '23 at 16:34

1 Answers1

2

No logical difference - the JS runtime will automatically figure out the "truthiness" of a statement.

I've seen this in a few places before (or the even more fun if(!!!x) instead of if(!x)) in the past.

<opinion> I think it has something to do with older JS runtimes that did a poor job of truthiness testing. I believe this to be an obsolete and overly verbose, if valid, construct.</opinion>

PaulProgrammer
  • 16,175
  • 4
  • 39
  • 56
  • RE: opinion - don't think this was ever the case. I've seen it used to explicitly denote that what's passed into the `if` is **not** a boolean. So there are fewer surprises after seeing the `if` itself. But it's mostly a coding style thing. – VLAZ May 09 '23 at 16:49
  • 1
    I'm assuming "older" here means from the 20th century, because I haven't seen anything that intensely weird since the "JScript" days. – tadman May 09 '23 at 16:55
  • I'm just trying to figure out a rationale for polluting code with nonsense. – PaulProgrammer May 09 '23 at 21:47