DEV Community

Kai
Kai

Posted on • Edited on • Originally published at kais.blog

How to Check For Undefined in JavaScript / TypeScript

This post was originally published at kais.blog.

Let's move your learning forward together! Follow me on Twitter for your daily dose of developer tips. Thanks for reading my content!


The correct way to check if something is undefined in JavaScript / TypeScript: Use the typeof operator! It returns a string showing the type of the unevaluated operand.

Let’s say you have an object user that looks like this:

const user = {
  email: "kai@example.com",
}
Enter fullscreen mode Exit fullscreen mode

If you use the typeof operator on the email and id property, you'll get this:

console.log(typeof user.email); // "string"
console.log(typeof user.id); // "undefined"
Enter fullscreen mode Exit fullscreen mode

Thus, to check for an undefined property you can combine an if-statement and the typeof operator:

if (typeof user.id === "undefined") {
  //
}
Enter fullscreen mode Exit fullscreen mode

Easy! Yet, there are other ways to check for undefined. However, those are sometimes quirky and will throw a ReferenceError. So, I suggest that you always use the typeof operator if you are checking for undefined.


Let's move your learning forward together! Follow me on Twitter for your daily dose of developer tips. Thanks for reading my content!

This post was originally published at kais.blog.

Top comments (2)

Collapse
 
janpauldahlke profile image
jan paul
Collapse
 
kais_blog profile image
Kai • Edited

Thanks for this addition. Nullish coalescing operator (??) and optional chaining (?.) are indeed very useful. Nevertheless, the real check for undefined is the one I've described. If you want to check if the property is undefined like in my example - a simple if-statement with typeof is the way to go.