In JavaScript, why would people write typeof myVar == "undefined"
instead of myVar == undefined
?
Is it for compatibility reasons?
This is the main reason:
if(a == undefined) console.log('test')
>> ReferenceError: a is not defined
if(typeof a == "undefined") console.log('test')
>> test
But if you run this comparison:
if(window.a == undefined) console.log('test')
>> test
So if you use a
as a standalone variable then you can't. Using window
it's possible, and doesn't really matter what approach will you use, but as I stated in comment it's safer to use typeof
as not every variable belongs to window
scope.