Reputation: 664
Here are two variables (technically, only a
is a variable, b
doesn't exist) in this JavaScript:
function func() {
var a;// a is declared but uninitialised
//var b; //b is commented out so b does not exist
}
How to tell a
from b
?
Both of them are typeof === 'undefined'
.
If a
is in the global scope, you can try 'a' in window
to tell it is Declared but Uninitialised. But what if it is in function scope?
How to tell if a JavaScript Variable is Declared but Uninitialised or Does not exist at all?
Upvotes: 0
Views: 155
Reputation: 31
I agree with the last two posters in that there is a difference between b as undefined and b being a reference error. A try catch would likely be the only way. I ran several logical tests on your scenario and b always throws an error when it is not in scope. In the fiddle, all the lines but one will error.
To prove it, uncomment one line at a time and run the fiddle.
function () {
var a;
console.log(a);
//if (a === b){ console.log('A and B are Undefined'); }//1)b is an error|2)
//if((typeof a) !== (typeof b)){ console.log('A is not B'); }//b is an error
//if(a && b){ console.log('Both a and b exist'); }//b is an error
//if(a || b){ console.log("a OR b exists"); }//b is an error
//if(a){ console.log('a exists'); }//A is not an error but does not write
//if(b){ console.log('b exists'); }//b is an error
//if(!a){ console.log('a exists but has no value'); }//a exists, but has no value, so writes
//if(!b){ console.log('b exists but has no value'); }/*b is an error*/
}
Good question because I thought a check on a non existent var should just be undefined also. I tested in chrome 51.0.2704.79 m.
I believe the result is logically correct. b does not even exist to the point that there is no name b, so cannot be referenced.
Hope this helps
Upvotes: 1
Reputation: 60527
You can use try
/catch
and see if it throws an exception. Non-existent variables will throw a ReferenceError
except when using typeof
.
function func() {
var a;
//var b;
try {
a;
}
catch (ex) {
console.log('a does not exist');
}
try {
b;
}
catch (ex) {
console.log('b does not exist');
}
}
func();
Well-formed code should not really depend on something like this though.
Upvotes: 2
Reputation: 1451
You can do try ... catch
and if it throws exception then the variable is not initialized.
var a;
try {
var value = a === b; // for example.
} catch(error) {
console.log('b is not declared');
}
Or you can create an object and check if it has corresponding properties:
var object = {};
object.a = undefined; // declared, not initialized
var hasA = 'a' in object; // or object.hasOwnProperty('a');
if(hasA) console.log('a is declared');
var hasB = 'b' in object; // or object.hasOwnProperty('b');
if(hasB) {
console.log('B is declared');
} else console.log('B is not declared.');
Upvotes: 0