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'
You can use both ways to check if the value is undefined
. However, there are little nuances you need to be aware of.
The first approach uses strict comparison ===
operator to compare against undefined
type:
var x;
// ...
x === undefined; // true
This will work as expected only if the variable is declared but not defined, i.e. has undefined
value, meaning that you have var x
somewhere in your code, but the it has never been assigned a value. So it's undefined
by definition.
But 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
.
x === undefined
does not work if variable is not declared. This returns true
only if variable is declared but not defined.
Better to use
typeof x === 'undefined'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With