I would like to find out if a Javascript variable exists. This is what I have so far which was cobbled together from different forums:
function valueOfVar(foo){
var has_foo = typeof foo != 'undefined';
if(has_foo){
alert('1 = true');
return true;
}
else {
alert('1 = false');
return false;
}
}
Please note, I wish to pass in a string as foo. Example: valueOfVar(box_split[0]+'_2')
Now, I don't think this works because it returns true when certain variables don't even exist. In fact, it seems to return true all the time.
A JQuery implementation that works would also be great as I make use of this.
Thanks all for any help
Do you mean something like this?
function variableDefined (name) {
return typeof this[name] !== 'undefined';
}
console.log(variableDefined('fred'));
// Logs "false"
var fred = 10;
console.log(variableDefined('fred'));
// Logs "true"
If you want to be able to handle local variables you'll have to do something quite weird like this:
function variableDefined2 (value) {
return typeof value !== 'undefined';
}
function test() {
var name = 'alice'
console.log(variableDefined2(eval(name)));
var alice = 11;
console.log(variableDefined2(eval(name)));
}
test();
// Logs false, true
The problem with your valueOfVar(box_split[0]+'_2')
test is that you are appending a string to the undefined attribute. You would always be passing a string to valueOfVar()
with the value of 'undefined_2'
.
You will notice that the typeof
operator will return 'string'
if you try the following:
function valueOfVar(foo){
alert(typeof foo);
}
valueOfVar(box_split[0]+'_2');
The typeof
operator would work for these kinds of tests, but you cannot append anything to the undefined variable, otherwise it would test always true:
if (typeof foo === 'undefined') {
// foo does not exist
}
else {
// it does
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With