null, undefined & NaN
JavaScript has three different ways to say 'nothing'. Learn the critical differences between these absence values.
The three absences
undefined means a variable has been declared but has not yet been assigned a value. It is JavaScript's default state of 'nothingness'.
null is an assignment value. It means you are intentionally stating that a variable holds 'nothing' or is 'empty'.
NaN stands for 'Not-a-Number'. It is the result of a mathematical operation that failed or an invalid type conversion (e.g. trying to divide a word by 2).
Why have both null and undefined?
Having two empty values is one of JavaScript's most criticized design flaws, but it can be useful. undefined usually means the system or engine hasn't provided a value yet. null means the programmer explicitly set the value to be empty.
By keeping this convention, you can look at a variable and immediately know if it's empty because you made it empty (null), or empty because you forgot to initialize it (undefined).
How to check for them
To check for null or undefined, always use strict equality (=== null). Do not use loose equality (==), because null == undefined evaluates to true!
Checking for NaN is uniquely difficult because NaN === NaN is actually false. NaN is the only value in JavaScript that is not equal to itself.
To reliably check if a value is NaN, use the built-in Number.isNaN(value) method.
The Nothingness Matrix
Observe how these three empty values behave differently when compared, checked for type, or used in math.
The Three Absences
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
undefinedmeans uninitialized.nullmeans intentionally empty.NaN === NaNis always false. UseNumber.isNaN()instead.typeof nullis'object'andtypeof NaNis'number'.
Done with this concept?
Mark it complete to track your progress. No login needed.