JavaScript check if undefined

July 15, 2019

How do I check if a variable is undefined in JavaScript?


typeof xyz === "undefined"
// ==> true

You might be tempted to check a variable with something like

if(!xyz) {
    // this will NOT WORK! It crashes because xyz is not defined
    console.log("not defined");

Doing so will lead to an error like the following:

Uncaught ReferenceError: xyz is not defined

So the solution is, as already mentioned to use the typeof operator

Interested in more content like this? Subscribe to my weekly Newsletter!