DEV Community

loading...

Discussion on: 💡 How to check if a variable is undefined in JS

Collapse
simonlegg profile image
Simon • Edited

I guess typeof has some builtin error handling. TIL.

xyz === undefined // throws Uncaught ReferenceError: xyz is not defined

typeof xyz === undefined // false

Edit: Interestingly, your suggestion works if the variable is in the “temporal dead zone”

xyz === undefined // true
typeof xyz === undefined // false
var xyz

Edit 2: Buuuuut, the above doesn’t work with block scoped variables!!

xyz === undefined // throws ReferenceError: Cannot access 'xyz' before initialization
typeof xyz === undefined // throws ReferenceError: Cannot access 'xyz' before initialization
let xyz
Collapse
jesperhoy profile image
Jesper Høy

I was too quick - what I meant was:

In other words - it works when qualified (if not in browser global scope, replace "window" with whatever xyz belongs to).

I have done this countless times and never thought to use typeof - which is why I felt the need to comment :-)

Thread Thread
benjaminmock profile image
Benjamin Mock Author

I see - but this is different. You're trying to access a non-existent property on a global object. That's of course not throwing a "Reference not defined" error, that's true.