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 JavaScript newsletters suck. That's why we made Bytes.

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

I pinky promise you'll love it, but here's a recent issue so you can decide for yourself.

Delivered to over 80,000 developers every Monday