Equality of null and undefined in JavaScript [Tech Interview Quiz]
In JavaScript, the values null
and undefined
are often used to represent the absence of a value or an
uninitialized variable. However, these two values can behave differently in certain situations, and it is important to understand the differences between them.
Seasoned interviewers often challenge Juniors to describe the concept of strict equality in JavaScript and how it applies to the values null
and undefined
.
Consider the following code snippet and determine the output.
Code snippet as a picture
|
|
What will be logged to the console?
Explanation
In the first line, we evaluate
null === null
and the result istrue
.In the second line, we evaluate
undefined === undefined
and the result istrue
once again.In the third line, however, we need to understand what the result of
null + undefined
is. For JavaScript, it’s hard to make sense of what it should be, so it evaluates this expression asNaN
.Now, is
NaN
equal toNaN
?And the answer is - NO.
In JS
NaN
is the only value that’s not equal to itself.
Answer
The output is going to be
true
,true
, andfalse
.