What is the best way to check if an element / variable is undefined
in Javascript?
I have already seen some examples using variavel === undefined
and others using typeof variavel == "undefined"
.
What is the best way to check if an element / variable is undefined
in Javascript?
I have already seen some examples using variavel === undefined
and others using typeof variavel == "undefined"
.
The correct way is to use typeof variavel === "undefined"
, since undefined
can be overridden using window.undefined
, causing variavel === undefined
comparison to return unexpected values.
In version 5 of ECMAScript, it is not possible to overwrite window.undefined
, although for compatibility with older engines it is recommended not to use this comparison format.
Note: Some people use if ( variavel ) {
to check if the variable is set. This is not trustworthy, since variavel
can have values that are interpreted as false
, and therefore not entering if
even if the variable is defined.
If you want to verify that variavel
has been declared, you should use the in
operator. This happens because when a variable is declared but not initialized explicitly, it is implicitly initialized with the undefined
value. Logo:
console.log(typeof x === "undefined"); // true
console.log("x" in window); // false
var x;
console.log(typeof x === "undefined"); // true
console.log(x in window); // true
The two checks you mentioned are for different things.
If a variable was not declared, with var variável = ...
, you can not use it in equality comparisons like if(variavel === undefined)
. This throws an error because the variable does not exist.
However, the typeof
operator accepts an operand that does not exist. Therefore, you can use typeof variavel == "undefined"
for this check. And this test with typeof
also serves to verify the second case:
undefined
An existing variable can contain the value undefined
. In this case, it is equivalent to check with variavel === undefined
or typeof variavel == "undefined"
- except in case the global variable undefined
has been overwritten as Vinícius quoted in his response, but this is no longer allowed by modern browsers.
Depends on what you want to test:
In this case, I would try to do an operation with it and observe a ReferenceError
:
var x;
try {
x + 1;
document.body.innerHTML += "<pre>x existe</pre>";
} catch(e) {
if ( e instanceof ReferenceError )
document.body.innerHTML += "<pre>x não existe</pre>";
else
throw e;
}
try {
y + 1;
document.body.innerHTML += "<pre>y existe</pre>";
} catch(e) {
if ( e instanceof ReferenceError )
document.body.innerHTML += "<pre>y não existe</pre>";
else
throw e;
}
In this case (and only then) you can test for its presence in the global object (in browsers , window
), as pointed out in Vinícius answer :
var a;
document.body.innerHTML += "<pre>a " + ("a" in window ? "" : "não ") + "existe.</pre>";
document.body.innerHTML += "<pre>b " + ("b" in window ? "" : "não ") + "existe.</pre>";
// Não funciona com variáveis locais a uma função
(function() {
var c;
document.body.innerHTML += "<pre style='color:red'>c " + ("c" in window ? "" : "não ") + "existe.</pre>";
document.body.innerHTML += "<pre>d " + ("d" in window ? "" : "não ") + "existe.</pre>";
})();
undefined
As pointed to by bfavaretto , a variable can be existing, valid, until it has already had value at some point , but at some point it may have received the undefined
value. In many cases this situation is indistinguishable from the case where the variable simply does not exist. But if you just want to know if it is different from undefined
- i.e. if it is defined - you can use typeof
:
var a = 10;
var b;
document.body.innerHTML += "<pre>a" + (typeof(a) == "undefined" ? " não" : "") + " está definida.<pre>";
document.body.innerHTML += "<pre>b" + (typeof(b) == "undefined" ? " não" : "") + " está definida.<pre>";
document.body.innerHTML += "<pre>c" + (typeof(c) == "undefined" ? " não" : "") + " está definida.<pre>";
undefined
? Compare with undefined
(or void(0)
) will cause a different response in each of the three cases above: it throws an exception if the variable does not exist, it returns true
if it exists but has undefined
, or it returns false
if it exists but has another value. Note that the comparison should always be done with ===
or !==
, never ==
or !=
(since the latter are too unpredictable to use safely).
"use strict";
var a = 10;
var b;
try {
document.body.innerHTML += "<pre>a" + (a === undefined ? " não" : "") + " está definida.</pre>";
document.body.innerHTML += "<pre>b" + (b === undefined ? " não" : "") + " está definida.</pre>";
document.body.innerHTML += "<pre>c" + (c === undefined ? " não" : "") + " está definida.</pre>";
} catch(e) {
document.body.innerHTML += "<pre>Erro: tentativa de acessar uma variável inexistente.</pre>";
}
Personally I consider it okay this way, since generally accessing a variable that was not defined is a programming error, not something you'll want to test running (except for debugging purposes, of course). Simply using variavel === undefined
and letting the exception propagate, if variavel
does not exist, it seems like an appropriate way of programming.
You can have a% generic "%" only pro program does not "explode" if an error of these goes unnoticed, but in my opinion it is useless to try to handle this exception. Because this situation is unexpected (if you expected, you would simply fix it and declare the variable!), Your program can hardly recover of this error .