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'
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'
Share
Improve this question
asked Feb 18, 2015 at 12:20
DonJuweDonJuwe
4,5634 gold badges37 silver badges60 bronze badges
1
- 2 possible duplicate of Detecting an undefined object property – Anatoli Commented Feb 18, 2015 at 12:24
4 Answers
Reset to default 12You 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 parison ===
operator to pare 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
parison 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
.
I guess both, depending on what you're testing? If it's a property, I'd always use x === undefined
, since it's clearer (and it seems faster).
As others said, x === undefined
won't work if x is not declared. Personally, I find that an even better reason to use it, since normally I shouldn't be checking if a variable is declared at all — it would usually be a sign of a coding mistake.
I've seen a lot of the other version for testing arguments — f = function(x) {if (typeof x == 'undefined') …}
— if I'm code-reviewing code like this I'll tell them to change it. We know for a fact the variable is declared, and making an habit of writing it that way increases the chance you'll waste time chasing typo bugs.
The main exception is when you're trying to check if a ponent or library was loaded or initialized correctly. if (typeof jQuery == 'undefined') …
makes sense. But in the medium term, all this should bee modules anyway, in which case the typeof test should in my opinion be phased out as harmful.
(Also, personally, I prefer if (window.jQuery === undefined)
for that case too. It's not portable for isomorphic code, though.)
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'
You could use any of them. If you would like to check if a variable is undefined or null you could use:
x == null
This results in true if x is undefined or null.