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
(Also0n
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 thatnull
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. ¯\_(ツ)_/¯
Equality (==) and Identity (===) Operators
(I never knew these are their real names haha when we are so used to calling these “strictly” or “loosely” equal to each other.)
When we are checking for null
and undefined
, it is quite interesting to take a look at the equality operators, as we performed type-conversion (or in a more technical term, type coercion) when we have to.
null == undefined
// true
null
and undefined
are loosely equal to each other (in this case, I would consider because they are both falsy value, so they are loosely equal to each other), however,
null === undefined
// false
null
and undefined
are not strictly equal to each other. I would consider because null
and undefined
have very different usage and meanings, that’s why they are strictly unequal to each other.
So, let’s put this in another way
null !== undefined
// true
Therefore, when null
is set to strictly unequal to undefined
, this would return us true
.
Practically speaking, let’s implement this into a if
statement (inspiration is completely from MDN):
So if we do
let woodstock; //undefined
if (woodstock === undefined) {
// whatever statement here executes
} else {
// this does not execute, since our variable is undefined, i.e. true
}
Pretty cool, right? Also I would like to point out another practical example I saw from another topic-related post.
With default parameters in a function, undefined
will use the default parameter while null
does not.
Let’s say we have a function peanuts
.
let peanuts = (str = 'snoopy is the best') => {
console.log(str);
}
Explanation: The code above creates a function called peanuts
. This function requires a string
parameter and it sets the default parameter to a string snoopy is the best
(of course.) if it isn’t provided.
Therefore, if we do
peanuts();
// snoopy is the bestpeanuts('charlie brown sucks at baseball')
// charlie brown sucks at baseball
If we insert the parameter as undefined
, it would give us the default value and not with null
:
peanuts(undefined)
// snoopy is the bestpeanuts(null)
// null
✨Bonus Section (ES2021 New Feature: Question question equals (??=))✨
As mentioned above, we would explore this new feature in ES2021 (Expected to release in June 2021!!!) that involves null
and undefined
that I found it interesting!
Before I get into the ??=
, I need to explain what ??
in a nutshell.
Nullish Coalescing Operator(??) in a Nutshell
There is a thing called nullish coalescing operator(??). This deserves its own article, but since we are on the topic of null
and undefined
, I would like to briefly talk about this. ||
is pretty common to a lot of us and we probably have seen and used this in multiple occasion. What about ??
? I mean, it’s not common for me.
The difference between ||
and ??
:
||
returns the right-hand side if the left-hand side is any falsy value, not only null
or undefined
.
const snoopy = null || "is not a usual beagle"
console.log(snoopy)
// is not a usual beagleconst woodstock = "" || "is a bird that can't fly"
console.log(woodstock)
// is a bird that can't fly
while
??
returns the right-hand side when the left-hand side is either null
or undefined
. Let’s use the above example for comparison:
const snoopy = null ?? "is not a usual beagle"
console.log(snoopy)
// "is not a usual beagle"const woodstock = "" ?? "is a bird that can't fly"
console.log(woodstock)
// ""
Note that “”
is a falsy value in JS, but with ??
, this would return ""
(empty string) anyway because it is neither null
nor undefined
.
Alright, let’s get into the real star here, the ⭐️Question question equals (??=)⭐️
Question Question Equals (??=)
(The Fancier Name: Logical Nullish Assignment)
This actually operates quite similarly to the Nullish Coalescing Operator(??). And if you think about how we use +=
, *=
, -=
, /=
, this ??=
works pretty similarly to those operators.
If we use +=
, this will look like this:
let a = 1;
console.log(a += 3); // 4
// same as: a = a + 3
??=
is pretty much in a similar nature:
let snoopy = null; // sorry snoopy!!!
let woodstock = "is better";snoopy ??= woodstock
// equivalent expression: snoopy ?? (snoopy = woodstock);
// snoopy will only be assigned to the woodstock variable if snoopy is null.
If we write this with the equivalent code of the if
statement with the same variable:
if (snoopy === null || snoopy === undefined) {
snoopy = woodstock;
}
This operator works quite similarly with the Nullish Coalescing Operator that it only checks for null
and undefined
, but not other falsy values.
This logical assignment operator is not the only new logical assignment operator in ES2021, there’re also &&=
and ||=
.
Yay! You made it to the end! Hope this article is helpful for you guys!! It’s always very exciting to learn new things!
(I’ve used a lot of Snoopy Gifs in my articles. Here’s one with Snoopy and Woodstock.)
Resources
Here are the few blogs that I used as reference for this article:
Blogs Related To ES2021 New Features to Look Out For!!