0

I am trying to write a convenience wrapper for console.log, and I would like to print any variables passed in along with their contents.

Can I turn a variable name into a string in js?

3
  • You mean, pass variables to a function as parameters and get the names of these variables? If so, it's not possible. It doesn't even make sense to write something like: myvariable.name. I don't get it Commented Sep 29, 2013 at 4:59
  • I don't think I understand your question. Commented Sep 29, 2013 at 5:03
  • 1
    No, it is not possible. Commented Sep 29, 2013 at 5:14

2 Answers 2

1

Assuming you want something like this:

function Log(data)
{
    console.log(input variable name, data);
}

Then I don't think it is possible:

For convenience.. you could do something like

console.log({ "your variable name": your variable});

Which turns the input to an object that does contain the variable name you want to log. A little more typing, but perhaps makes the console output more readable.

Sign up to request clarification or add additional context in comments.

Comments

0

There is a possibility. And here is how

var passed_variable = '65'; // The actual variable
var varname = 'passed_variable'; // The name of the variable in another variable

Now, pass the varname around but not the actual variable. When you need to the value of the variable you can simply do :

console.log(varname, ' : ', window[varname]); // Outputs, passed_variable : 65

I hope you find a way not to use this. :)

10 Comments

unless passed_variable resides in the global space, it won't be visible as window[varname]. And I don't want to have to put my variables in the global scope in order to log them.
and, of course, prefixing something with var is something you do when you don't want it to end up in the global scope - in which case the log explicitly won't work (unless the code itself is in global scope, in which case the var keyword is merely pointless)
@JanDvorak, Yeah the implication is it being in a global scope.
which var does the exact opposite of. Even if this is fixed, though, it's still a bad way to do your average-day logging.
@JanDvorak No var used inside a function or scope limiter does that.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.