hookedonwinter hookedonwinter - 1 month ago 11
Javascript Question

Javascript: Reference a variable name from the variable itself

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:



--

Edit: I'd love to just call
varlog(foo)
, if the name "foo" can be derived from the variable.

Answer

The reason it doesn't work is because the variable foo is not accessable to the function varlog! foo is declared in someRandomFunction, and is never passed into varlog, so varlog has no idea what the variable foo is! You can solve this problem by passing the variable foo into the function(or using some sort of closure to make foo in the scope of varlog) along with its string representation, but otherwise, I think you are out of luck.

Hope this helps.