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