0

I am trying to place if statements inside of a function with conditions based on the NAME of the parameter used in the function, not the value.

What conditions can be used to achieve this? Is it possible? If not, is there and alternative?

For example:

var lorem="The name is Lorem, but the value isn't.";
var ipsum="The name is Ipsum, but the value isn't.";
//the values shouldn't matter

logIt(Lorem);

function LogIt(theName){
    if(**the name of the variable theName = "lorem"**){
    console.log("The variable 'lorem' was used.");
  }else if(**the name of the variable theName = "ipsome"**){
    console.log("The variable 'ipsum' was used.");
  }else{
    console.log("huh?");
  }
}
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
kennsorr
  • 292
  • 3
  • 20

1 Answers1

0

I believe it's not really possible to get the name of the variable in the general case, since argument values are copied to function parameters.

That said, if you only have a fixed set of variable names and you are using ES6, you could technically "hack" around the problem with object destructuring:

var lorem="The name is Lorem, but the value isn't.";
var ipsum="The name is Ipsum, but the value isn't.";

Logit({lorem}) 

function Logit({lorem, ipsum}) {
   if(lorem) console.log("Function called with lorem");
   else if(ipsum) console.log("Function called with ipsum");
   else console.log("Function called with something else");
}
Amal Antony
  • 6,477
  • 14
  • 53
  • 76
  • Well you might wanna take a look at this answer it already mentions that it is possible http://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript . The concept used there is of dynamic variables. There must be some other way as well. – rresol Mar 04 '17 at 19:26