Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using typeof vs === to check undeclared variable produces different result

If I have an undeclared variable and use typeof it tells me it's undefined. But if I then check it using if (qweasdasd === undefined) it throws an exception.

I don't understand this behavior, because if the first tells undefined, then the second check should evaluate to if (undefined === undefined), why does it throw a ReferenceError exception?

like image 353
Konstantin Milyutin Avatar asked Jul 28 '15 09:07

Konstantin Milyutin


1 Answers

typeof looks like a function call, but it is not - it is an operator. Operators are allowed to break rules. typeof(qweasdasd) does not assume qweasdasd exists; whether it exists or not and what it is is what typeof exists to discover. However, when you test qweasdasd === undefined, you are using qweasdasd as a value, and JS complains when you use a variable that you haven't assigned a value to.

like image 188
Amadan Avatar answered Sep 28 '22 18:09

Amadan