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? Commented Aug 25, 2010 at 10:47
  • I find this code extremely weird. I wonder what you're trying to accomplish? Commented 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. Commented 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/… Commented 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. Commented 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') 
Sign up to request clarification or add additional context in comments.

6 Comments

Just a comment, why would I pass a harcoded string value 'foo' when I know I am going to get it as return value?
@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.
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)
This could be useful for refactoring during debugging..
You can write function getName(variable){ return Objects.keys(variable)[0]} and call it this way var abc = "xyz"; console.log(getName({abc}));
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.