5

I understand that !! converts anything to a boolean value, but why would you want to do this:

if (!!someObject) { ... }

When you can just do:

if (someObject) { ... }

EDIT:

Just to clarify, I'm simply asking why you would write code like in the first example, rather than that in the second example. Are there any practical differences?

Derek Chiang
  • 3,330
  • 6
  • 27
  • 34
  • see: http://stackoverflow.com/questions/784929/what-is-the-not-not-operator-in-javascript – Jerzy Zawadzki Jul 28 '13 at 00:06
  • For example `return !!5` or `!!~arr.indexOf(n)`. There are many uses not just `if` statements. – elclanrs Jul 28 '13 at 00:06
  • 1
    @elclanrs I understand, but I was asking specifically about the use in the first example. – Derek Chiang Jul 28 '13 at 00:09
  • 2
    There's no real use for `!!` in `if` statements AFAIK. You can rely on truthyness or falsyness. – elclanrs Jul 28 '13 at 00:11
  • `!!` is only useful in an `if` when you want to perform a comparison, e.g. if you want to check two things are both truthy or both falsy you could do `if (!!a === !!b) {/*..*/}`. Edit: if that were for numbers, then it _could_ mean "`a` and `b` are both `0` OR `a` and `b` are both non-zero" – Paul S. Jul 28 '13 at 00:31
  • @PaulS. that makes sense, although this usage sounds pretty obscure :P – Derek Chiang Jul 28 '13 at 00:47

1 Answers1

1

There isn't a significant different between them. So, most likely, it's personal preference or to be explicit about the intent.

Though, it's possibly from an uncertainty/misunderstanding of how or when values are treated as a booleans.

But, both if statements and Logical NOT operators use the internal ToBoolean():

If ToBoolean(GetValue(exprRef)) is true, [...]

Let oldValue be ToBoolean(GetValue(expr))

The operators just add 2 more rounds of ToBoolean() with negation on top of the if statement's own use. But, the result is the same.

Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199