How do I check if a variable is undefined in JavaScript?
tldr
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
Top comments (10)
Why not just
xyz === undefined
?
I guess
typeof
has some builtin error handling. TIL.Edit: Interestingly, your suggestion works if the variable is in the “temporal dead zone”
Edit 2: Buuuuut, the above doesn’t work with block scoped variables!!
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 :-)
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.
The best option when you don't know something about JS is check for it in the spec...
ecma-international.org/ecma-262/10...
UnaryExpression
: typeofUnaryExpression
val
be the result of evaluatingUnaryExpression
.Type(val)
isReference
, then a. IfIsUnresolvableReference(val)
istrue
, return"undefined"
.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.
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
In my opinion, it's better to introduce the problem first then give the solution at the end of the article.
Thank you
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.
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
oruser.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.