This question:
JavaScript check if variable exists (is defined/initialized)
does not regard the case of variables which have been declared but not defined (as opposed to undeclared and undefined). Specifically, if I want to check whether x
has been declared, this:
typeof x == 'undefined'
will not do, because...
var x; //<- declared but undefined
// idontexist not declared
typeof idontexist === typeof x; // evaluates to true
This has implications: if variable has been declared it wont become a global variable, whereas if a variable has not declared, it would become a global variable, possibly leading to memory leak.
So how do I check in javascript if undefined variable has been declared?
Regarding the implications of this, consider this code:
function test() {
var x
console.log(typeof x == typeof y); // true
if (typeof x == 'undefined') {
x = 3;
}
if (typeof y == 'undefined') {
y = 5;
}
}
test();
y; // 5
x; // Reference Error