0

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"
5
  • There is a question with (close to) exact same title available on SO. See SO question stackoverflow.com/questions/7983896/… Commented Oct 5, 2014 at 12:42
  • No, it's not possible. Commented Oct 5, 2014 at 12:45
  • What's the purpose of this anyway? Commented Oct 5, 2014 at 12:55
  • That's an XY problem. Why do you want to do this? I've never come across a case where this was needed. Commented Oct 5, 2014 at 13:03
  • xkcd.com/293 Commented Oct 5, 2014 at 13:04

1 Answer 1

1

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 ;)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.