2

I was wondering if it's possible to get the name of a variables in javascript or JQuery.

Suppose that I declare a variable in javascript like:

var customerNr = "456910";

If a function receive a variable, how can i return the name of the variable?

For example:

function getNameOfVariable(someVariable){
     //return name of someVariable;
}

If I call this function like this:

getNameOfVariable(customerNr);

The function has to return a string whose value is "customerNr".

How can I do this in jquery or javascript? Some kind of reflection?

Juan Jardim
  • 2,232
  • 6
  • 28
  • 46
  • 3
    You can't, or rather you shouldn't! You can use eval or other tricks to sort of do this, but at the end of the day you're probably doing something wrong if you need the name of the variable. – adeneo Sep 07 '13 at 14:13

2 Answers2

1

That is simply not possible!

The passed parameter doesn't even have to have a name. It could be a return value of a function or a raw literal (like "string" or 3).

ComFreek
  • 29,044
  • 18
  • 104
  • 156
0

No, this is not possible. Only values are transferred for primitive data types, not references, so how would you know what the "name" of the variable is? For example:

var customerNr="456910";
var customerNrAfterProcessing=customerNr;
getNameOfVariable(customerNrAfterProcessing);

Would it return customerNrAfterProcessing or customerNr?

However, you can imitate this behavior with objects.

var variableName = someMethodThatDeterminesVariableNameOrJustAConstantIfYouPrefer();
var myVariables={};
var myVariables[variableName]={};
myVariables[variableName].value="456910";
myVariables[variableName].variableName=variableName;

function getNameOfVariable(someVariable){
    return someVariable.variableName;
}
getNameOfVariable(myVariables[variableName]);

Obviously, this amounts to a lot more work than just using the variableName variable directly, but it could be necessary in some more complicated situations.

See working with objects in JS reference

Flight Odyssey
  • 2,267
  • 18
  • 25
  • 1
    If one imitates the behaviour in the way you do, you can just pass the name along the parameters: `func(myVariable, 'myVariable')` – ComFreek Sep 07 '13 at 14:20