Distinguish the "undefined" value of typeof from a non-existent variable of a defined one with the value undefined

0

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 (returning "undefined" as well) independently if it is You have assigned that value manually or not. My question is: how is it possible to differentiate between those that are defined with an assigned undefined value from those that have not been defined? Plasma in the example: How to get me to detect that c has not been defined unlike a and b, that if they are in spite of having an undefined value?

    
asked by Adrià Fàbrega 26.11.2017 в 10:24
source

1 answer

2

The only way you can verify if a variable has been declared, is to contain it within a try/catch waiting for it to launch ReferenceError when accessing the variable:

try{
 c;
}catch(error){
  if(error.name === 'ReferenceError') {
   console.log("la variable 'c' no ha sido declarada");
  }
}

If I throw the error then it is because it is not declared, otherwise it is because if it is.

As you have already noticed, the operator typeof does not throw an error but treats it as undefined . Even if window.c or window['c'] were used, this would return undefined equally:

console.log(window.c);
console.log(window['c']);

Update

I was wrong, if there are other ways to check if a variable was declared. As suggested by @Jose Hermosilla Rodrigo , use hasOwnProperty(prop) can also indicate whether a variable was declared or not:

if(window.hasOwnProperty('c')){
  console.log('variable c definida')
}
else{
 console.log('variable c no definida')
}

Note that if you need to know if it is declared within a function, hasOwnProperty will not work unless you indicate the context in which you are going to look for the property:

var global = "variable global";

var fn = function(){
  console.log(this.hasOwnProperty('c'))
}

fn(); // 'false' porque no esta declarada dentro de la funcion fn

fn = function(){
  var c = '';
  console.log(this.hasOwnProperty('c'))
  console.log(this.global); // this representa window por lo que podemos acceder a las variables definidas en window
}

fn(); // 'false' tambien ya que this representa el objeto window

new fn(); // 'false, undefined' por igual debido a que 'c' no esta declarada en el contexto de la funcion fn, sino de forma privada y la variable global dara undefined debido a que no esta declarada en el contexto this

fn = function(){
  this.c = ''; // la agregamos al contexto de la funcion
  console.log(this.hasOwnProperty('c'))
}

new fn(); // como si esta declarada en el contxto de fn() entonces si es posible encontrar la variable 'c'

In summary, you have to make sure you're looking in the correct context (object) when you use the hasOwnProperty function.

There is also the operator in that verifies if the object has a certain property defined and the same context rule applies to it as hasOwnProperty :

console.log('c' in window)
    
answered by 26.11.2017 / 12:19
source