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",
}
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.
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)
Have a look at the new syntax sugar here: developer.mozilla.org/en-US/docs/W...
or
developer.mozilla.org/en-US/docs/W...
Thanks for this addition. Nullish coalescing operator (
??) and optional chaining (?.) are indeed very useful. Nevertheless, the real check forundefinedis the one I've described. If you want to check if the property isundefinedlike in my example - a simpleif-statement withtypeofis the way to go.