Whenever I encounter
I decided to do some research to gain a deeper understanding of the two data types. It's helpful to have this knowledge so that you can use them correctly when needed. I've also learned that sometimes, the difference between
undefined comes up in interviews. 👀
Null is an assignment value, which means that you can assign the value
null to any variable when you want that variable to be empty. It is intentionally left blank and will point to an empty value.
let hasCat = null; // nullish
Undefined is a variable that exists but hasn't been initialized YET. Which means that later, I can come back to my variable and assign it a value that it did not have before. So if I declare a variable without a value, it's just considered non-initialized.
let currentJob; // undefined
null == undefined; // truthy null === undefined; // falsey
Imagine you're moving. You bought a bunch of boxes. You have to pack up your stuff and put them inside of those boxes. But you're disorganized so you forget to label what's in the boxes. You have 5 boxes that are full of things and you have 2 boxes that are left empty. You want to label your boxes but you've already put tape on them, so you tell yourself you'll come back to it later. For now the 5 boxes are TBD. And the 2 boxes are leftover and empty. In code, that would look like:
let fiveBoxes = undefined; let twoBoxes = null;
The five boxes with a bunch of stuff in them are considered undefined because they have things in them but you don't know what's in it YET. The two boxes left empty are MEANT to not have anything in them.
The difference between the two data types is:
- Engine Assigned
- Lack of
- User assigned
Go to your console, and type in:
typeof null typeof undefined
What do you get?
Null and undefined are not the same. It's important to learn the difference between the two so you avoid any buggy behavior in your code and have a clear understanding of why they exist. It's also cool if you're able to clearly state the difference in an interview too 😉
Feel free to hit me up on Twitter if you're still confused! Or if you'd just like to chat.