Null and Undefined in JavaScript
What’s the difference between null and undefined? We are going to find out in this article. (Bonus section with the new feature of ES2021)
I have learned JavaScript for several months, but I still could not differentiate null and undefined. This may sound silly, I know. So, in this article, I decided to dive deep the differences between the two.
Before we start, we have to understand the 7 primitive data types: string number bigint boolean undefined null symbol
And there are 6 common known falsy values in Javascript(full list), which are: keyword false number 0 and -0 (Also 0n and -0n ) Empty string values: “”, '' , `` null (the absence of any value) undefined NaN — not a number
As we can see, null and undefined are treated as falsy for boolean operations. There is something I would like to discuss that are added into ES2021 (or ES12) that is related to null and undefined , which we would explore at the end of this article.
Let’s explore together what the differences are between null and undefined !
Null
According to MDN , null represents the intentional absence of any object value.
null must be assigned. Interesting thing about null is that null expresses the lack of identification, meaning the variable points to no object.
Undefined
A variable that has not been assigned a value is considered a type of undefined . A method or statement would return undefined if the variable does not have an assigned value, so as a function.
Code Example:
What if I assigned the variable snoopy to null ? If I console.log the variable, the terminal would print null . On the other hand, when I assigned snoopy to nothing and console.log that:
This would print undefined . You can also explicitly assigned variable to undefined , it would give you the same result regardless:
Quick Note: As mentioned earlier, null and undefined are both primitive values, but interestingly enough, if we test out in typeof , they gave us different result:
All other values in Javascript are objects ({}, [], functions…). So, this is generally regarded as a mistake when Javascript is first created.