I want to create a quick function that will console.log a variable name and the value. I’d like the result of the function to show in the console: foo: bar.
My basic idea for the function looks like this:
function varlog(var_name)
{
console.log(var_name + ": " + eval(var_name));
}
And I’d call is thusly:
function someRandomFunction()
{
var foo = "bar";
// ... some stuff happens
varlog("foo");
}
This works if foo is global, but doesn’t work in the example provided. Another option that also only works globally is using window[var_name] instead of the scary eval.
I don’t think what I’m asking is possible, but I figured I’d throw it out there.
I’m spending a lot of time attempting to be lazy. My current method is just console.log('foo: ' + bar); which works just fine. But now I just want to know if this is possible.
Some other questions I referenced in searching for this / creating what I have now:
- Variable name as a string in Javascript
- How to convert variable name to string in JavaScript?
- Javascript, refer to a variable using a string containing its name?
- How to find JavaScript variable by its name
—
Edit: I’d love to just call varlog(foo), if the name “foo” can be derived from the variable.
The reason it doesn’t work is because the variable
foois not accessable to the functionvarlog!foois declared in someRandomFunction, and is never passed intovarlog, sovarloghas no idea what the variable foo is! You can solve this problem by passing the variablefoointo the function(or using some sort of closure to makefooin the scope ofvarlog) along with its string representation, but otherwise, I think you are out of luck.Hope this helps.