2

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.

2
  • 3
    console.log("max_value"); ? Commented May 25, 2015 at 7:45
  • why do you need this? what exactly do you want to achieve? Commented May 25, 2015 at 7:54

1 Answer 1

2

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 ){});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.