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.
a === undefined. For the second, use linters and watch your developer console so you can fix bugs where you forgotvar a. Don't use unnecessarytypeofhacks that hide useful error messages and allow bugs to go undetected.