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

As I understand it, the preferred way to check for undefined variables is typeof a === 'undefined' .

But why is it better than typeof a == 'undefined' ? In what places can this happen?

+4
source share
4 answers

In this case, since typeof will always give you a string: this is no better (and no worse). This is not practical.

In general, using === is preferable because it forces you to be explicit about your types and saves you from getting results that you don't expect when JavaScript type resolution rules are unintuitive.

+8
source

The difference between == and === is that == performs conversions. So, for example, 1 will be == to '1' , but not === to '1' . The reason this approach is preferable when you check for undefined is because JavaScript has known barriers to comparison.

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 avoid the null == undefined problem, which can lead to hard-to-reach errors. This is why you should use == instead of === . Since === does not perform any conversions behind the scenes, this is also a faster operation.

In this particular case, this will not affect the result. Whether you use typeof a == 'undefined' or typeof a === 'undefined' , the output will be the same without error. This is because typeof returns a string. However, the operation will be faster, so you will have a slight increase in productivity.

+5
source

Because typeof will only return a string, so it is safe to compare two strings with == .

+3
source

There is a big difference between == and === ( here)

But, since typeof will always return a string, this is normal to use.

+1
source

All Articles