2

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.

6
  • 2
    Possible duplicate of JavaScript check if variable exists (is defined/initialized) Commented Dec 7, 2016 at 17:56
  • If by default variable a is undefined, then check (typeof a == "undefined"). Commented Dec 7, 2016 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. Commented Dec 7, 2016 at 17:57
  • @Dekel my question is about "best way" to check, no "how to". Sorry my bad english. Commented Dec 7, 2016 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...) Commented Dec 7, 2016 at 18:04

1 Answer 1

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");
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.