As I understand the prefered way to check undefined variables is typeof a === 'undefined'
.
But why it is better then typeof a == 'undefined'
? In which places can it fail?
As I understand the prefered way to check undefined variables is typeof a === 'undefined'
.
But why it is better then typeof a == 'undefined'
? In which places can it fail?
- 1 @Jake1164 why it's duplicate? There is parision with "null" in that question. – Paul Annekov Commented Apr 22, 2013 at 11:20
4 Answers
Reset to default 10In this instance, since typeof
will always give you a string: It isn't better (nor is it worse). It makes no practical difference.
In general, using ===
is preferred because it forces you to be explicit about your types and saves you from getting results you don't expect when JavaScript's type resolution rules are unintuitive.
The difference between ==
and ===
is that ==
performs conversions. So for instance 1 will be ==
to '1'
but not ===
to '1'
. The reason why that approach is preferred when you check for undefined
is because in JavaScript there are known parison pitfalls.
The most mon:
'' == '0' //false
0 == '' //true
0 == '0' //true
false == 'false' //false
false == '0' //true
false == undefined //false
false == null //false
null == undefined //true
" \t\r\n" == 0 //true
So with ===
you are avoiding the null == undefined
problem, which can lead to hard-to-find bugs. That's why you should use ==
instead of ===
. Because ===
is not performing any conversions behind the scenes, it is also a faster operation.
In this specific case, it won't make a difference effect-wise. Whether you use typeof a == 'undefined'
or typeof a === 'undefined'
the output will be the same, with no bugs. That's because typeof
returns a string. However, the operation will be faster, so you have a negligible performance increase.
Because typeof
will only return string, so it is safe to pare two strings with ==
.
There is a big difference between ==
and ===
(Check out here)
But, since typeof will always return string, it's ok to use this.