In JavaScript, the null
and undefined
datatypes are most confusing, especially for freshers. They behave in a very strange and many general rules do not apply to them.
Before deep-diving into their strange behavior, let's first understand what null
and undefined
is.
Undefined
The meaning of undefined
is "no value assigned". If a variable is declared but not assigned then its value is undefined
.
let firstName;
console.log(firstName); // undefined
We can also explicitly assign undefined
to a variable.
let a = 25;
a = undefined;
console.log(a) // undefined
However, explicitly assigning undefined
to a variable is not recommended. It is a bad code practice.
null
null
in JavaScript means 'empty', 'nothing' or 'unknown value'. It is not a "reference to non-existing object" like in some other programming languages. The below code simply means that the age
value is unknown.
let age = null;
Comparision with null and undefined
The behavior of null
and undefined
is strange when compared to other values.
For a strict equality check ===
console.log(null === undefined) // false
Their values are different because each of them is of a different type.
For non-strict check ==
console.log(null == undefined) // true
The result is clearly different than expected. As a general rule, the non-strict check ==
converts the values to numbers if they are of different types.
So, Number(null) = 0
and Number(undefined) = NaN
. Ideally, they should not be equal. But the result shows true
.
This is an exception which we have to keep in mind
For maths and other comparisons < > <= >=
,
null
and undefined
are converted to numbers: 0
and NaN
respectively.
null vs 0
Let's see how null
behaves when compared with 0.
console.log( null > 0 ) // false
console.log( null == 0 ) // false
console.log( null >=0 ) // true
Now you might be scratching your head. If the last line is true, then why above two lines are false?
When we use null
with ==
it is simply treated as null
only. But when used with comparisons, it is converted to 0.
So, 0>=0
is true, and 0>0
is false.
undefined vs 0
Let's see how undefined
behaves when compared with 0.
console.log( undefined > 0) // false
console.log( undefined == 0 ) // false
console.log( undefined >=0) // false
undefined
when used with comparisons, it is converted to NaN
and when used ==
it is treated as undefined
only. Hence the output is as above.
That's all in this blog folks. If you liked it, do share it. Suggestions and edits are welcome.