1

Well, my question is obvious,

Example:

Define a with default value undefined:

var a;

If I want to check if a var exists, I will try with:

But in this case, a does exists and a value is undefined, but in the boolean evaluation this is false.

var a; // default value is 'undefined'
if (a) {
    alert('a exists');
} else {
    alert("a don't exists")
}

I can also try with the following example: but this example generates a error.

// var a;
// a is not defined
if (a) {
    alert('a exists');
} else {
    alert("a don't exists")
}

And in this example, I try with typeof. But a is defined with undefined value by default.

var a;
if (typeof a != 'undefined') {
    alert('a exists');
} else {
    alert("a don't exists")
}

And in this example

console.log ('var a exists:', window.hasOwnProperty('a'));

What is the best way to verify if a variable actually exists and why?

Thanks.

dda
  • 6,030
  • 2
  • 25
  • 34
Olaf Erlandsen
  • 5,817
  • 9
  • 41
  • 73
  • 2
    Possible duplicate of [JavaScript check if variable exists (is defined/initialized)](http://stackoverflow.com/questions/5113374/javascript-check-if-variable-exists-is-defined-initialized) – Dekel Dec 07 '16 at 17:56
  • If by default variable a is undefined, then check (typeof a == "undefined"). – MCMXCII Dec 07 '16 at 17:57
  • For the first, `a === undefined`. For the second, use linters and watch your developer console so you can fix bugs where you forgot `var a`. Don't use unnecessary `typeof` hacks that hide useful error messages and allow bugs to go undetected. –  Dec 07 '16 at 17:57
  • @Dekel my question is about "best way" to check, no "how to". Sorry my bad english. – Olaf Erlandsen Dec 07 '16 at 18:03
  • 1
    If you double check the content of the question there is "Which method of checking if a variable has been initialized is better/correct?", which is almost the same is "best way" :) (check all the answers there...) – Dekel Dec 07 '16 at 18:04
  • To determine which approach is "best", we need to know [what you actually need this for](http://meta.stackexchange.com/q/66377). – Bergi Dec 07 '16 at 18:09

1 Answers1

4

There are three different possibilities in JS for a variable.

  1. Variable 'a' not at all declared;
  2. Variable 'a' declared, but unassigned (undefined). Ex: var a;
  3. Variable 'a' declared, but assigned with empty or null. (Possible scenario, if a variable trying to get value from back-end)
    Ex: var a=null; var a='';

If you are expecting a value in variable, other than 0 or false, then better to use following condition. And of course its all based on your need and if you unsure about variable or object values, always enclose them in try & catch block.

//var a;
//var a=null;
//var a='';
//var a=0;
//var a='value';

if (typeof a != "undefined" && a) {
  alert("a is defined AND a is TRUE value");
} else {
  alert("a not exist OR a is a FALSE value");
}
NallaRK
  • 41
  • 5