JS / explain undefined, null, and NaN
icncsx
Posted on May 28, 2020
We all know that null
, undefined
and NaN
are falsy values, but what are their different use cases and where do they commonly appear? Here's a TL;DR version I've come with.
Undefined
Undefined is always the default value of unassigned variables. We rarely if ever in practice assign undefined to a variable because JavaScript does that automatically for us. Every declared variable is initialized to undefined by default, and it's our job to replace that with an assigned value of our choice.
let someVar;
console.log(someVar) // undefined
null
Unlike undefined, null is never assumed by default. Null is typically used when we want to reset a variable; this is typically more clear than reassigning a variable to an empty string, 0, or undefined. It's null. Something happened, and we're explicitly resetting a variable to nothing - aka null. You will also frequently encounter null as a return value of a function. It's pretty context driven as to what that really means, so I'll leave it up to you to figure it out.
NaN
Last but not least, there is NaN (not a number). Ironically though, NaN is of type number and therefore can be used in calculations. If you ever use NaN in a calculation, the result is also NaN. Think of NaN as like an error in a mathematical context. You made an invalid calculation, so this is what you get: NaN.
Most recently, I encountered NaN when I was multiplying a DOM node with an integer. How silly!
// incorrect
const priceEl = document.getElementById("invoice");
const quantity = 4;
console.log(price * quantity); // NaN
This is what I should have done!
// correct
const price = parseFloat(document.getElementById("invoice").innerHTML);
const quantity = 4;
console.log(price * quantity); // YaY, I got my total price
Admittedly, this was a pretty long read. So much for TL;DR... I'm sorry if you feel tricked (😅). Here's the real TL;DR:
- undefined
- default value of uninitialized variables
- null
- never assumed by default
- explicitly typed by the programmer to signal many different things: the resource doesn't exist, something went wrong, etc.
- NaN
- of type number and can therefore be used in calculations
- used to signal that a miscalculation took place
PS: Admittedly, I'm not sure if I'm doing a good job with these pedagogic blog posts, so I need feedback! I would greatly appreciate it if you could leave some helpful reviews below (😁).
Warmly,
EK
Posted on May 28, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.