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 - tired of boring JavaScript newsletters? Us too. That's why we made Bytes.

The goal was to create a JavaScript newsletter that was both insightful and entertaining. 40,000 subscribers later and well, reviews don't lie

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

43,092 Subscribers. Every Monday.