How to Check undefined or null in JavaScript (ES2020 way)

How to Check undefined or null in JavaScript (ES2020 way)

ยท

4 min read

๐Ÿ‘‹ Hey, there. What is the most common way you crash your program? For me, it's trying to de-reference null or undefined by accident. I still remember the first bug I created to crash a live website (bad idea to code in prod), staring at the 404 page and the following error message to try to figure out what went wrong.

Screen Shot 2021-01-31 at 4.13.50 PM.png

How can I check if the variable is either undefined or null before trying to access it? If you put this blog title to search bar you might find some solutions like:

if ( typeof( user ) != 'undefined' && user != null ) {
  // Do something with user like user.name
}

This works fine but what if user is a nested object, do I just keep adding condition to the if block? That doesn't sound like a good solution.

if ( typeof( user ) != 'undefined' && user != null && 
     typeof( user.profile ) != 'undefined' && user.profile != null ) {
  // Do something with user.profile.name
}

The Solution

Introducing, the Optional chaining operator ( ?. ), this operator functions similarly to the . chaining operator, except that instead of causing an error (if user or profile is null or undefined), the expression short-circuits with a return value of undefined immediately. This will avoid error with a simple check

if ( user?.profile?.name ) {
  // Do something with user.profile.name
}

Great! Now you can access any nested property with confidence.

Bonus - combining with ?? Operator

Sometimes we want to assign default value to an undefined or null variable, we use:

const name = user.name || 'default username';

This works in most of the cases except when user.name is 0 (don't ask me why someone would name 0 while " X ร† A-12 " is a real name). In fact, default value will be assigned if user.name is any of the falsy value (false, '', NaN, 0, undefined)

We can use the nullish coalescing operator (??) instead, so

const name = user?.name ?? 'default username'
// default value will only assign if left-side of ?? is null or undefined

Summary

Above is the ES2020 way to check for null and undefined, by simply append a ? after the variable, and we also see an example how the optional chaining operator ( ?. ) working with nullish coalescing operator ( ?? ).

Thank you for spending time to read my first Hashnode post! If at lease one person find it useful that will totally make my day. Let me know by dropping a comment!

Cheers! ๐Ÿฅณ