How to check for undefined in JavaScript

This is one of those topics where the strange history of the JavaScript language clouds what is now an easy solution. In this post we’ll ignore that history (cause it’s been fixed) and look at the two predominant ways to check if a value is undefined in JavaScript today, not 10 years ago.

Best Solution

The way I recommend to check for undefined in JavaScript is using the strict equality operator, ===, and comparing it to the primitive undefined.

if (user === undefined) {
  // user is undefined
}

Checking for `undefined this way will work in every use case except for one, if the variable hasn’t been declared yet. Admittedly, this is a rare occurrence which is why I recommend the solution above.

Other Solution

In cases where you’re not sure if a variable has been declared, you can use the typeof operator and compare it to the string of 'undefined'.

if (typeof notSureIfDeclared === 'undefined') {

}

One more thing

Hear me out – most newsletters are trash. At best they're boring and at worst they're spam.

With Bytes, we wanted to create something you actually looked forward to reading. It's like if you combined tc39 meeting notes with an Old Spice commercial.

I pinky promise you'll love it, but here are some recent issues so you can decide for yourself.

30,716 Subscribers. Every Monday.