DonJuwe DonJuwe - 7 months ago 17
Javascript Question

Best practice of checking if variable is undefined

I was having some issues in my conditions concerning undefined variables. What is, to sum it up, the best way to check if a variable is undefined?

I was mainly struggling with

x === undefined


and

typeof x === 'undefined'

Answer

You can use both ways to check if the value is undefined. However there are little nuances you must remember.

The first way is using strict comparison === to compare with undefined type:

x === undefined; // true

This will work as expected only if the variable is declared but has undefined value. If variable is not declared with var keyword above code will throw reference error:

x === undefined // ReferenceError: x is not defined 

In situations like these, typeof comparison is more reliable:

typeof x == 'undefined' // true

which will work properly in both cases: if variable has never been assigned a value, and if its value is actually undefined.