We all come across null, undefined and NaN at some point in our coding journey. As a beginner, I'd always wanted to know how and why these special values behave the way they do. So I'm going to illustrate just that in this article.
Null represents an empty value and carry no meaningful information.
Undefined represents any value that has not been defined anywhere in the program.
If any variable or operation isn't able to produce a meaningful value, it returns undefined.
let a = [1,2] console.log(a) //undefined
In the above example, there is no meaningful value for a because it doesn't exist, so it returns undefined
NaN stands for Not a Number. You get this value when you try to do some operation that can't yield a meaningful result. If you use the typeof operator on NaN, it shows it is a number.
console.log(0/0) //NaN console.log("five" * 2) //NaN console.log(typeof(NaN)) //number
Let's have a look at how these values behave with each other, and why.
console.log(undefined===false) //false console.log(undefined===true) //false console.log(null===false) //false console.log(null===true) //false
null and undefined return false when compared with any value. Or does it? Let's take a look.
console.log(null==undefined) //true console.log(null===undefined) //false
Before going into the explanation, let's take a look at how "==" and "===" work.
"==" performs a loose equality operation between its operands and does type coercion.
Whereas "===" performs a strict equality and does not try to convert the type of either value. It checks if the type of the values are the same. If not it returns false.
Now let's get back to the code. Let's look at the two cases.
null and undefined are both falsy values and that is why it returns true in the first line. Also == operator needs its operands to contain some value. Since null and undefined don't contain any value, it returns true.
Since null and undefined are of different types, it returns false.
So null and undefined return true only when they're loosely compared with each other.
Let's make it a little interesting.
console.log(!!NaN) //false console.log(!NaN) //true console.log(NaN === true) //false console.log(NaN === false) //false
Since NaN is a falsy value !NaN returns true.
NaN is not equal to any value. It always returns false.
- null and undefined are values that contain nothing.
- null and undefined are loosely equal to each other but are strictly not equal to each other.
- NaN is a result of nonsensical computation which cannot produce a meaningful result.
- NaN is the only value which isn't equal to itself.
I hope this clears some of your doubts about these special values. And I hope you enjoyed reading this!