Damjan Pavlica
Damjan Pavlica

Reputation: 33993

Is it possible to log variable name in JavaScript?

Is it possible to log variable name (not value) in JavaScript?

var max_value = 4;
console.log(max_value); // should log "max_value" as a string

UPDATE: I need a testing function that should be able to log any variable name (passed as an argument) as a string, not just this one variable.

Upvotes: 2

Views: 325

Answers (1)

Khalid
Khalid

Reputation: 4808

There is a solution that can help you. I grabbed this function from this stackoverflow answer, which is able to get the name of the function parameters:

var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var ARGUMENT_NAMES = /([^\s,]+)/g;
function getParamNames(func) {
  var fnStr = func.toString().replace(STRIP_COMMENTS, '');
  var result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);
  if(result === null)
     result = [];
  return result;
}

then all you need to do now, is to use the name of your variable as a parameter of an anonymous function and pass all the function as argument of the getParamNames :

variablesNames = getParamNames(function (max_value, min_value) {});

This will return an array like this :

result => ["max_value", "min_value"];

Let's make it practical, first change the name of the getParamNames function to something easy and small like this :

function __ (func) {
   // code here  ...
}

second thing, instead of returning an array, just return the first element of the array, change this :

return result;

to this :

return result.shift();

now, you can get the name of your variable like this :

__(function( max_value ){});

Upvotes: 2

Related Questions