Determine original name of variable after its passed to a function

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


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.

Tags:

Javascript