Determine original name of variable after its passed to a function

Viewed 10346

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.

8 Answers

As you want debugging (show name of var and value of var), I've been looking for it too, and just want to share my finding.

It is not by retrieving the name of the var from the var but the other way around : retrieve the value of the var from the name (as string) of the var.

It is possible to do it without eval, and with very simple code, at the condition you pass your var into the function with quotes around it, and you declare the variable globally :

foo = 'bar';

debug('foo'); 

function debug(Variable) { 
 var Value = this[Variable]; // in that occurrence, it is equivalent to
 // this['foo'] which is the syntax to call the global variable foo
 console.log(Variable + " is " + Value);  // print "foo is bar"
}

I think you can use

getVariableName({foo});

Use a 2D reference array with .filter()

Note: I now feel that @Offermo's answer above is the best one to use. Leaving up my answer for reference, though I mostly wouldn't recommend using it.

Here is what I came up with independently, which requires explicit declaration of variable names and only works with unique values. (But will work if those two conditions are met.)

// Initialize some variables
let var1 = "stick"
let var2 = "goo"
let var3 = "hello"
let var4 = "asdf"


// Create a 2D array of variable names
const varNames = [
    [var1, "var1"],
    [var2, "var2"],
    [var3, "var3"]
]


// Return either name of variable or `undefined` if no match
const getName = v => varNames.filter(name => name[0] === v).length
  ? varNames.filter(name => name[0] === v)[0][1]
  : undefined


// Use `getName` with OP's original function
function getVariableName(unknownVariable){
  return getName(unknownVariable)
}

Related