Skip to content

JavaScript Null Checks and Type Coercion

by Jeff

There are many discussions of JavaScripts type coercion at work, and many examples of the distinction between undefined and null. This becomes very important when performing checks for null and undefined.

Here’s an easy summary:

JavaScript distinguishes between null, which is an object of type ‘object’ that indicates a deliberate non-value, and undefined, which is an object of type ‘undefined’ that indicates an uninitialized value.

While this distinction is made, undefined == null. This is due to JavaScripts type coercion. The two operands do NOT have to be of the same type to yield true for equality, as JavaScript automatically performs conversion on a differing operand.

So:

  • 1==true  // evaluates to true
  • “1″==true // evaluates to true
  • 45==”45″ // evaluates to true
  • null==undefined // evaluates to true

If the last bullet doesn’t seem to make as much sense, you’re not alone.

In a lot of cases, you’re not going to want to evaluate objects with this coercion. For those cases, strict evaluation is allowed with ===. No coercion is performed in this case.

So:

  • true===1  // evaluates to false
  • NaN===NaN // evaluates to false
  • var x=[1,2]
  • var y=[1,2]
  • x===y // evaluates to false
  • undefined === null // evaluates to false

var healthCare = {
exists: true
};

healthCare.exists // will be true
healthCare.isExpensive // will be undefined

Lastly, double negation can be used in JavaScript to convert any value to a Boolean object.

if(!!healthCare.exists) // will be true

if(!!healthCare.isExpensive) // will be false

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

One Comment

  1. Two of your examples of the behavior of the strict equality test don’t really distinguish it from the loose equality test. Both (NaN!=NaN) as well as ([1,2]!=[1,2]) are true statements using the loose equality test.

    Thursday, December 24, 2009 at 9:02 pm | Permalink

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*