The undefined vs null Pitfall in Javascript

Sometimes I come across JavaScript code with a lot of null checking against properties that are uninitialized, which is really wrong. Many people might think that uninitialized properties get a default value of null, but that is not the case despite having something like foo == null resulting in true, assuming foo is an undefined variable in this example.

The result mentioned above is the way it is, because the == operator does type coercion so that it can compare the two for their values. Thus when you do something like foo == null (Equality), JavaScript automatically converts it to the type null so it can carry out the comparison on two values with the same types, and obviously in this comparison the result will end up being true.

On the other hand if you did foo === null (Identity) which checks for both type and value the result will be false which is the correct result because there is a type mismatch between the two. foo's type is undefined while null is an object. You can check that for yourself via typeof(null) and typeof(undefined). Actually null is not really an object but a primitive value in JavaScript. Having typeof(null) output "object" is considered to be a bug in the language. Despite that, the point here is that null and undefined are of different types anyways.

A property that has no definition is undefined, which also means no value, no type and never been referenced before in the scope. On the other hand, null is where the property exists but it isn't known what its value is.

As a general rule, it is good to use === instead of == in JavaScript when comparing values especially when there is a huge possibility that your program will end up comparing values of different types at some point. What is dangerous about == is that it performs all kinds of conversions between types which could produce unexpected results in your program.

Enjoyed this post? Help me spread the word and let me know your feedback!
Fork me on GitHub