12

Possible Duplicate:
Determine original name of variable after its passed to a function.

I would like to know if its possible to get the actual name of a variable.

For example:

var foo = 'bar';
function getName(myvar) {  
  //some code
  return "foo"  
};  

So for getName(foo) will return "foo"

Is that possible ?

Thanks.

7
  • 2
    why would you be interested in variable name? Rather your logic in functions should depend on variable values right? Aug 25, 2010 at 10:47
  • I find this code extremely weird. I wonder what you're trying to accomplish?
    – axel_c
    Aug 25, 2010 at 10:50
  • Never seen it done, why would you need it anyway? You already know it. It sounds like you should restructure your scripts to remove this neccessity.
    – Tom Gullen
    Aug 25, 2010 at 10:50
  • Luckily this isn't possible in JavaScript, otherwise you'd end up with something horrible³ like this... stackoverflow.com/questions/2749796/…
    – Ivo Wetzel
    Aug 25, 2010 at 10:56
  • 1
    This is pretty useful feature if you trying build a debugger or auto register a namespace without redeclaring or declaring another variable. I see some extremely useful cases for this.
    – flyandi
    Apr 15, 2015 at 21:02

1 Answer 1

8

I don't think it is possible. When you call a function you pass an object, not a variable. The function doesn't care where the object came from.

You can go the other way though if you call your function as follows:

getName('foo') 

Or pass both the value and the name:

getName(foo, 'foo') 
6
  • 2
    Just a comment, why would I pass a harcoded string value 'foo' when I know I am going to get it as return value? Aug 25, 2010 at 11:25
  • @Sachin Shanbhag: How exactly will you get it as a return value if you don't pass it in as a parameter? You're assuming that what the OP is asking is possible. Perhaps it is... but I'd really like to see some evidence of that please.
    – Mark Byers
    Aug 25, 2010 at 11:27
  • 1
    I know it's way old, but for future reference... It does help in programming, in some very speficic features, it's actually possible in c# using the nameof operator (wrong results if used for arguments as the OP wanted, but I believe he wouldn't need a function). I came to this exactly with a need. Think about it when you have a process to change other process parameters and you want the other process to react to some specific parameters changes. Would be very fragile to do something like if (argumentName == 'myArgument') because the name could change. Rather == nameof(myArgument) Aug 14, 2017 at 12:31
  • 1
    This could be useful for refactoring during debugging..
    – tBlabs
    Oct 2, 2017 at 8:27
  • 3
    You can write function getName(variable){ return Objects.keys(variable)[0]} and call it this way var abc = "xyz"; console.log(getName({abc}));
    – itsmnthn
    Oct 9, 2020 at 13:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.