Reputation: 20628
I usually test whether a JavaScript variable is defined or not, using the following test:
if (typeof a == 'undefined')
a = 'default value'
However, I have seen many people suggesting that it is safer to use the following instead:
if (typeof a === 'undefined')
a = 'default value'
I am aware of the difference between ==
and ===
operators but I am unable to understand why typeof a == 'undefined'
could be unsafe.
Could you please a scenario in which the first code example is unsafe or could lead to issues? Also, what are the advantages of using the latter syntax over the first?
Upvotes: 1
Views: 163
Reputation: 56467
Since typeof a
is always a string then ==
and ===
will always yield the same result, i.e. there is no significant difference between them ( the only one is that one is longer then the other ;) ).
Warning, personal opinion: I find ==
operator completely horrible. How could anyone think that it is a good idea to have two different comparison operators? There is no other language where two objects of different type can be equal. This is insane. Thus people tend to use ===
all the time, because it is a good practice. So I guess that in this situation it is just a habit... a good habit.
Upvotes: 4
Reputation: 71908
I am unable to understand why
typeof a == 'undefined'
could be unsafe
It's not unsafe, it's perfectly fine. The typeof
operator is guaranteed to return a string, so you'll always be comparing two strings. The abstract equality algorithm will behave just like strict equality.
Upvotes: 6