0

I know this is completely useless, but I'm nonetheless curious. Is it possible to do something like the below?

function getVariableName ( v )
{
    // .... do something ..... 
    // return the string "v" 
}
var x = 69;
var y = "somestring";
console.log(getVariableName(x)); // prints "x" to the console
console.log(getVariableName(y)); // prints "y" to the console
phts
  • 3,889
  • 1
  • 19
  • 31
Depak Chopra
  • 307
  • 2
  • 6

1 Answers1

-2
function getArgNames(fn) {
    var matches = fn.toString().match(/\(([a-z_, ]+)\)/i);
    if (matches.length > 1) {
        return matches[1].replace(/\s+/g, '').split(',');
    }
    return [];
}

That will return an array of the names of all arguments passed in to the function.

Randy Hunt
  • 435
  • 3
  • 10
  • 1
    This returns the *formal* parameter names - the names from the function definition. The OP wants the names of variables referenced in calls to the function - the *actual* parameters. – Pointy Apr 09 '15 at 17:36
  • Ah, right. It satisfied the "V" example, but not the X and Y conditions. :-/ – Randy Hunt Apr 09 '15 at 17:38