How do I check a variable if it\'s null
or undefined
and what is the difference between the null
and undefined
?<
The spec is the place to go for full answers to these questions. Here's a summary:
x
, you can:null
by direct comparison using ===
. Example: x === null
undefined
by either of two basic methods: direct comparison with undefined
or typeof
. For various reasons, I prefer typeof x === "undefined"
.null
and undefined
by using ==
and relying on the slightly arcane type coercion rules that mean x == null
does exactly what you want.==
and ===
is that if the operands are of different types, ===
will always return false
while ==
will convert one or both operands into the same type using rules that lead to some slightly unintuitive behaviour. If the operands are of the same type (e.g. both are strings, such as in the typeof
comparison above), ==
and ===
will behave exactly the same.More reading: