DEV Community

Cover image for 💡 How to check if a variable is undefined in JS

💡 How to check if a variable is undefined in JS

Benjamin Mock
I'm Ben, a Frontend Developer from Germany working at ebay
Originally published at ・1 min read

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

Discussion (10)

jesperhoy profile image
Jesper Høy

Why not just

xyz === undefined


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
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.

mgtitimoli profile image
Mauro Gabriel Titimoli • Edited

The best option when you don't know something about JS is check for it in the spec...

UnaryExpression: typeof UnaryExpression

  1. Let val be the result of evaluating UnaryExpression.
  2. If Type(val) is Reference, then a. If IsUnresolvableReference(val) is true, return "undefined".
estevanjantsk profile image
Estevan Jantsk

I'm wondering why would you add a variable inside an if if you didn't at least declared or received that variable as a parameter.

benjaminmock profile image
Benjamin Mock Author

It might be because you don't know if a variable is declared or not. e.g. You have a global window object in the browser, but not in Node.js

skopetn profile image
Skander Guarbàa

In my opinion, it's better to introduce the problem first then give the solution at the end of the article.

Thank you

ggenya132 profile image
Eugene Vedensky

Wait, pardon my ignorance but isn't undefined a 'falsy' value? Based on my own local testing, this won't throw an error. I do however agree that implicit boolean testing is not a best practice.

martinmuzatko profile image
Martin Muzatko

What are the use-cases?
In web applications where we mostly deal with handing data from one instance to another (database -> service -> restapi -> front-end -> render). The chances are, you almost never need type checking.
Is it undefined? Well don't send it in the first place or let the database handle it.

All these checks belong to the data instance where it is coming from. So the database has to do all the checking to make sure you are not giving it NULL when it does not allow it. Or if you use a file with JSON, the author needs to make sure it is valid.

And I can think of plenty cases where implicit boolean tests are just fine and do the job.

Like: rendering a string based on its existence

Say you have a vue/react/angular/whatever app that only renders the

tag if a users address details are available.
Here we don't need to check for typeof user.address !== undefined or user.address !== undefined && user.address !== null && typeof user.address == 'string
It is simply enough to check for a truthy value. so if(user.address) render() is doing the job just fine. By the contract of the data objects given by the rest api, we know that user.address will be either undefined or a string containing the address. The user might fill in a random string, a random number or whatever. It is the backend and frontend validations job to not let invalid values pass into the database, and the database as last resort can still reject it.

As for undefined variables. I never have this problem. I explicitly require or import libraries and I define variables. I avoid race conditions at all times.