Monday, June 29, 2015

JavaScript: What is Null? Baby don't hurt me, don't hurt me no more...

Variable comparison among the bestiary of undefined, null, 0, NaN, and empty values -- with apologies to Haddaway

JavaScript is a powerful scripting language, suitable for general programming tasks in addition to its traditional role in powering active web pages.  As the language grows in popularity, programmers who traditionally used Perl, Python or Ruby to solve server-side tasks have embraced it for many applications, especially when combined with Node.js.

One of the most powerful yet confusing features of JavaScript is its automatic behaviors for handling the assignment and comparison of objects, strings, and numerical values.  In order to make effective use of JavaScript, you must know the rules.  Nowhere is this more important than when dealing with undefined, null, invalid, and empty values.

In Short, the following values are all distinct in JavaScript:
  • undefined -  A non-object, non-value.  An uninitialized variable or object reference.
  • null - An object that exists (is defined) but that has been explicitly assigned a value of "null", which is neither numerical nor a string.  Comparing a null variable to "null" returns true; However comparing two variables holding null values results in false.
  • NaN - Not a Number, the result of an invalid numerical operation, e.g. division by zero.  Comparing a NaN variable to NaN returns false.  Comparing two NaN values for equality also returns false.
  • "" - An empty string.
  • 0 - Zero.
  • false - boolean false.
But what is equal?

When considering tests for undefined, null, and the like, we must pay attention to whether the variable is an object, an object member, or a primitive.  We also need to pay attention to the type of comparison operator we use.

The standard equality comparison operator ==, along with its variations !=, <=, >=, <, >, will attempt to compare two values after recasting them to the same type.

The strict equality comparison operator === will return false of the two values being compared are not of the same type.