Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typeof a == 'undefined' vs typeof a === 'undefined'

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?

like image 724
Paul Annekov Avatar asked Apr 22 '13 11:04

Paul Annekov


2 Answers

In 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.

like image 70
Quentin Avatar answered Oct 01 '22 18:10

Quentin


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 comparison pitfalls.

The most common:

''        ==   '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.

like image 21
flavian Avatar answered Oct 01 '22 20:10

flavian