-1

I recently got some JS code and I saw very often statements like the following:

if(object) {
  //do something
}

or

if(object.attr) {
      //do something
    }

Is this a short form for if(object !== undefined) or for if(object !== null)?

d4rty
  • 3,970
  • 5
  • 34
  • 73

1 Answers1

3

It's a short form for

if (object !== "" && 
    !Number.isNaN(object) &&
    object !== 0 &&
    object !== false &&
    object !== undefined &&
    object !== null)

The isNaN() check is a little tricky; the "old" global isNaN() would coerce its parameter to a number, so passing a string like "foo" to isNaN() returns true, even though the string "foo" isn't really NaN. The newer isNaN() method on the number constructor doesn't perform that coercion, so Number.isNaN("foo") is false.

Note that when checking for the existence of an object property there's an ambiguity with undefined. It's possible for a property to be present on an object but have no value. The in operator is useful in such cases:

if ("something" in object)

tests whether the object has a property named "something" regardless of value.

Pointy
  • 405,095
  • 59
  • 585
  • 614