How to Check For Undefined in JavaScript / TypeScript

published

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: "[email protected]",
}

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"

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

if (typeof user.id === "undefined") {
  //
}

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.


If you like my content and you want to see more, please follow me on Twitter!

You May Also Be Interested in the Following Posts