Find out if a variable exists

I would like to know if a Javascript variable exists. This is what I still have that has been ground from various forums:

function valueOfVar(foo){ var has_foo = typeof foo != 'undefined'; if(has_foo){ alert('1 = true'); return true; } else { alert('1 = false'); return false; } } 

Note that I want to go into a string like foo. Example: valueOfVar (box_split [0] + '_ 2')

Now I do not think this works because it returns true when some variables do not even exist. In fact, he seems to be returning all the time.

A jQuery implementation that works will also be great as I use this.

Thank you all for your help.

+6
javascript jquery
source share
3 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 need to do something rather strange:

 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 
+6
source share

The problem with the valueOfVar(box_split[0]+'_2') test valueOfVar(box_split[0]+'_2') is that you are adding a string to the undefined attribute. You will always pass a string to valueOfVar() with the value '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 will work for these types of tests, but you cannot add anything to the undefined variable, otherwise it will always check true:

 if (typeof foo === 'undefined') { // foo does not exist } else { // it does } 
+1
source share

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

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

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

0
source share

All Articles