Let's take an example:
var a; //hereda el valor undefined automaticamente
var b = undefined; //se le asigna el mismo valor pero manualmente
//Si accedemos a los tipos
console.log(typeof a); //"undefined"
console.log(typeof b); //"undefined"
console.log(typeof c); //"undefined"
//Si accedemos a los valores
console.log(a); //undefined
console.log(b); //undefined
console.log(c); //ERROR: c is not defined
if(typeof c !== "undefined"){ //Si introduzco tanto a, como b o como c...
console.log("La variable c SÍ ha sido definida");
} else {
console.log("La variable c NO ha sido definida"); //...el resultado siempre será este.
}
We can see that the operator typeof
gives the same treatment to both an undefined variable (returning "undefined"
) and one that has been defined but with an undefined value ( "undefined"
also returning) regardless of whether that value has been assigned manually or not. My question is: how is it possible to differentiate between those that are defined with an assigned undefined value and those that have not been defined? Captured in the example: How can I get it to detect that c has not been defined, unlike a and b, that they are despite having an undefined value?
The only way you can check if a variable has been declared is by containing it inside a
try/catch
waiting for it to be thrownReferenceError
when the variable is accessed:If I throw the error then it is because it is not declared, otherwise it is because it is.
As you may have already noticed, the operator
typeof
does not throw an error but treats it asundefined
. Even ifwindow.c
or was usedwindow['c']
, this would return theundefined
same:Update
I was wrong, yes there are other ways to check if a variable was declared. As @Jose Hermosilla Rodrigo suggests , using
hasOwnProperty(prop)
can also indicate whether or not a variable was declared:Keep in mind that if you need to know if it is declared inside a function,
hasOwnProperty
it will not work for you unless you indicate the context in which it is going to look for the property:In short, you have to make sure that you are looking in the correct context(object) when you use the
hasOwnProperty
.There is also the operator
in
that checks if the object has a certain property defined and the same context rule is applied to it ashasOwnProperty
: