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?
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?
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.
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. :)
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.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)var does the exact opposite of. Even if this is fixed, though, it's still a bad way to do your average-day logging.var used inside a function or scope limiter does that.