Abs
Abs

Reputation: 57916

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

Upvotes: 6

Views: 11259

Answers (3)

Rich
Rich

Reputation: 3123

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

Upvotes: 6

Daniel Vassallo
Daniel Vassallo

Reputation: 344311

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
}

Upvotes: 1

Warty
Warty

Reputation: 7395

Not sure if this addresses your problem, but in JavaScript, null is not the same thing as undefined. The code you wrote is correct for testing if a variable isn't defined. IE:

<script>
window.onload = function()
{
     alert(typeof(abcd) == "undefined"); //true
     abcd = null;
     alert(typeof(abcd) == "undefined"); //false
};
</script>

By the way, the type of null is "object".

Upvotes: 0

Related Questions