Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out if a Variable exists

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

like image 221
Abs Avatar asked Feb 20 '10 22:02

Abs


2 Answers

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
like image 84
Rich Avatar answered Oct 01 '22 11:10

Rich


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
}
like image 21
Daniel Vassallo Avatar answered Oct 01 '22 10:10

Daniel Vassallo