What are the differences between null, undefined, and NaN?
All three are JavaScript data types. All three evaluate to false. The keywords are all case-sensitive. Let’s see how they are different:
null is a the only one that is acknowledged as having a type of object, but it is not the same as an empty object:
var a = null;
var b = {};
console.log(a === b); // false
Even though null returns object as its type, we can’t check the length of keys on null because it “can’t be converted to an object.”
console.log(typeof(a)); // object
console.log(Object.keys(a).length);
// TypeError: Cannot convert undefined or null to object
JavaScript considers null to be a defined value representing the absence of a value. Think how white is the absence of pigment and also the name of a color that we recognize. Similarly, JavaScript can recognize when something is null.
undefined, on the other hand, is not considered a value. JavaScript says, “I don’t know what this is. It is not defined.” Even though they both evaluate to false, null is not identical to undefined because null is defined. Care to guess what type undefined is?
var a = null;
var b = undefined;
console.log(a == b); // true
console.log(a === b); // false
console.log(typeof(b)); // undefined
NaN is a value returned by a function expecting to return a number but instead returns a value, of type number, that is not a number. Read that again. Like null, NaN is defined. It is also a built-in error message informing us of a specific problem.
var a = NaN;
var b = undefined;
console.log(a == b); // true
console.log(a === b); // false
console.log(typeof(a)); // number
Each NaN is unique.
var a = NaN;
var b = NaN;
console.log(a == b); // false
Related posts:
Helpful references:
Have feedback on this topic?