2

Very often we check our objects if they are not null and not undefined. I always use condition if (obj !== null && obj !== undefined). Few days ago my colleague shown me the syntax of double inversion !! and now I can use condition if (!!obj). This syntax is less.

I'm not a person who are only learning js, but I have a little interest.

So is there any difference between these two ways of object validation? Performance difference? Semantic difference? Any difference?

Andrew
  • 1,444
  • 4
  • 19
  • 27
  • 1
    `!!obj` is definitely not the same. It will also be `false` for `0`, the empty string and `NaN`, not only for `null` and `undefined`. – Frédéric Hamidi Feb 02 '16 at 10:24
  • You rather should use `obj != null` (which is also semantically equivalent to your longer expression) – Bergi Feb 02 '16 at 10:28

2 Answers2

3

There isn’t any particularly good reason to ever use if (!!obj), as it’s equivalent to if (obj). !!obj and obj !== null && obj !== undefined do different things, though, and you should use whichever’s most appropriate.

  • obj !== null && obj !== undefined (surprise, surprise) results in false for null and undefined.
  • !!obj results in false for anything falsy, including null, undefined, '', 0, NaN, and false.
Ry-
  • 199,309
  • 51
  • 404
  • 420
0

!!foo is used to force coerce a value into its Boolean value. This is, in my experience, often used in APIs that want to return a Boolean value for a value that contains sensitive data. For example, to return whether or not a password is entered you might say return !!password rather than return password.

Continuing on that, if (!!obj) is not the same as if (obj !== null && obj !== undefined) for many values you can think of! Such as false.

Steve Klösters
  • 9,337
  • 2
  • 39
  • 53