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") {
}

Before you leave

I know, "another newsletter pitch" - but hear me out. Most JavaScript newsletters are terrible. When's the last time you actually looked forward to getting one? Even worse, when's the last time you actually read one rather than just skim it?

We wanted to change that, which is why we created Bytes. The goal was to create a JavaScript newsletter that was both educational and entertaining. 84,512 subscribers and an almost 50% weekly open rate later, it looks like we did it.

Delivered to 84,512 developers every Monday

Avatar for Tyler McGinnis

Tyler McGinnis

CEO of ui.dev. Obsessed with teaching, writing, swimming, biking, and running.

Share this post