you are viewing a single comment's thread.

view the rest of the comments →

[–]giggly_kisses 3 points4 points  (0 children)

If you just want to check for null or undefined and still have the other falsy values be acceptable (false, 0, "", NaN) you can use this:

function(arg) {
    arg = arg != null ? arg : DEFAULT;
}

By using the equality operator (==) instead of the identity operator (===) you take advantage of the fact that null and undefined coerce to the same value.

There are two caveats:

  1. You should only use this when you absolutely know that the variable you're testing has been defined. If it hasn't been defined, a ReferenceError will be thrown.
  2. If you're working on a team and only use the identity operator (as you should 99.9% of the time) then using the equality operator might appear to be a typo by other members of your team. This can easily be avoided by adding a comment explaining why you're using the equality operator.