user2370460
user2370460

Reputation: 7820

JavaScript convert variable name into string

I have a function like:

function testFunction( option )
{
  alert(option);
}

(the actual function does more than just answer the option)

And of course, it works if you do testFunction("qwerty");, or testFunction(myvar);, where myvar is a variable.

It does not work if I do testFunction(qwerty);, where qwerty is not a variable, as expected.

I was wondering if there is a way to make the function check to see if option is a variable or string (such as "qwerty" and myvar in the examples above) and if it is continue as normal and alert the string or the variable's value.

However, if it is not a variable or string, but is an undefined variable (such as qwerty in the example above) then I would like it to alert the name of the variable (qwerty in this case).

Is this possible?

Thanks!


Some more examples:

var myvar = "1234";
testFunction("test"); //alerts "test"
testFunction(myvar);  //alerts "1234"
testFunction(qwerty); //alert "qwerty"

Upvotes: 0

Views: 1422

Answers (1)

xShirase
xShirase

Reputation: 12399

Your problem here is that testFunction(qwerty); will not even reach the function.

Javascript cannot interpret the variable 'qwerty' as it is not defined, so it will crash right there.

Just for fun, here's a way to do what you request, by catching the error thrown when you try to interpret an undefined variable :

function testFunction( option ){
      console.log(option);   
}


try {
    var myvar = "1234";
    testFunction("test"); //alerts "test"
    testFunction(myvar); 
    testFunction(qwerty); //alert "qwerty" 
}catch(e){
    if(e.message.indexOf('is not defined')!==-1){
       var nd = e.message.split(' ')[0];
       testFunction(nd);
    }
}   

JSFiddle here

Bear in mind that you should absolutely never do that, instead, try using existing variables in your programs, it works better ;)

Upvotes: 1

Related Questions