Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine original name of variable after its passed to a function

Tags:

javascript

I've got a feeling this might not be possible, but I would like to determine the original variable name of a variable which has been passed to a function in javascript. I don't know how to explain it any better than that, so see if this example makes sense.

function getVariableName(unknownVariable){
  return unknownVariable.originalName;
}

getVariableName(foo); //returns string "foo";
getVariableName(bar); //returns string "bar";

This is for a jquery plugin i'm working on, and i would like to be able to display the name of the variable which is passed to a "debug" function.

like image 744
Andy Groff Avatar asked Aug 04 '10 09:08

Andy Groff


People also ask

What is the variable name that is used by a function to receive passed value?

The data passed to the function are referred to as the "actual" parameters. The variables within the function which receive the passed data are referred to as the "formal" parameters.

How do you pass a variable name as an argument in Python?

Use a dict. If you really really want, use your original code and do locals()[x][0] = 10 but that's not really recommended because you could cause unwanted issues if the argument is the name of some other variable you don't want changed. Show activity on this post. Show activity on this post.

Can we define the variable as name?

A variable is a symbolic name for (or reference to) information. The variable's name represents what information the variable contains. They are called variables because the represented information can change but the operations on the variable remain the same.


2 Answers

You're right, this is very much impossible in any sane way, since only the value gets passed into the function.

like image 137
deceze Avatar answered Oct 12 '22 10:10

deceze


This is now somehow possible thanks to ES6:

function getVariableName(unknownVariableInAHash){
  return Object.keys(unknownVariableInAHash)[0]
}

const foo = 42
const bar = 'baz'
console.log(getVariableName({foo})) //returns string "foo"
console.log(getVariableName({bar})) //returns string "bar"

The only (small) catch is that you have to wrap your unknown variable between {}, which is no big deal.

like image 39
Offirmo Avatar answered Oct 12 '22 11:10

Offirmo