9

I want to create a log function where I can insert variable names like this:

var a = '123',
    b = 'abc';

log([a, b]);

And the result should look like this in the console.log

a: 123
b: abc

Get the value of the variable is no problems but how do I get the variable names? The function should be generic so I can't always assume that the scope is window.

4
  • 4
    This isn't possible in Javascript as you want it to work. With something like var foo = bar = {} the same object is referred to by 2 names, and if you just pass the object into a function it's impossible from inside the function to reverse that lookup and see which name was used to pass it in.
    – Gareth
    Apr 23, 2012 at 7:10
  • Ok then I can stop searching. Thanx!
    – arpo
    Apr 23, 2012 at 7:18
  • Instead, you should learn how to use a debugger. Start by putting a line just containing debugger instead of your console.log line, and then run your code with Firebug or Chrome Inspector open
    – Gareth
    Apr 23, 2012 at 7:26
  • 1
    Exact duplicate of How to convert variable name to string in JavaScript? Mar 10, 2014 at 13:56

7 Answers 7

6

so the argument is an array of variables? then no, there is no way to get the original variable name once it is passed that way. in the receiving end, they just look like:

["123","abc"];

and nothing more


you could provide the function the names of the variables and the scope they are in, like:

function log(arr,scope){
    for(var i=0;i<arr.length;i++){
        console.log(arr[i]+':'scope[arr[i]]);
    }
}

however, this runs into the problem if you can give the scope also. there are a lot of issues of what this is in certain areas of code:

  • for nonstrict functions, this is window
  • for strict functions, this is undefined
  • for constructor functions, this is the constructed object
  • within an object literal, this is the immediate enclosing object

so you can't rely on passing this as a scope. unless you can provide the scope, this is another dead end.


if you pass them as an object, then you can iterate through the object and its "keys" and not the original variable names. however, this is more damage than cure in this case.

2

I know you want to save some keystrokes. Me too. However, I usually log the variable name and values much like others here have already suggested.

console.log({a:a, b:b});

If you really prefer the format that you already illustrated, then you can do it like this:

function log(o) {
    var key;
    for (key in o) {
        console.log(key + ":", o[key]);
    }
}

var a = '1243';
var b = 'qwre';
log({
    a:a,
    b:b
});

Either way, you'd need to include the variable name in your logging request if you want to see it. Like Gareth said, seeing the variable names from inside the called function is not an option.

1
  • Yes that's perhaps the closest I can get.
    – arpo
    Apr 23, 2012 at 8:00
1

Something like this would do what you're looking for:

function log(logDict) {
    for (var item in logDict) {
        console.log(item + ": " + logDict[item]);
    }
}

function logSomeStuff() {
    var dict = {};
    dict.a = "123";
    dict.b = "abc";
    log(dict);
}

logSomeStuff();
2
  • I Know I can use a object. What I want to do is to save key strokes when I'm working. I want to quickly see what a bunch of variables is. If I have to put them into an object I get key strokes but of another kind :) I'm tired of typing console.log('a: ' + a ' b: ' + b); and want a function to handle that.
    – arpo
    Apr 23, 2012 at 7:11
  • In that case, you run into the scope-related issues that @Joseph mentions in his answer. Apr 23, 2012 at 7:19
0

Don't know if this would really work in JS... but you can use a Object, in which you can store the name and the value:

  function MyLogObject(name, value) {
    this.name = name;
    this.value = value;
  }


  var log = [];
  log.push(new MyLogObject('a', '123'));
  log.push(new MyLogObject('b', 'abc'));

  for each (var item in log) {
    if (item.value != undefined)
      alert(item.name + "/" + item.value);       
  }

Then you can loop thru this Object and you can get the name and the value

1
  • No an object is not what I'm looking for.
    – arpo
    Apr 23, 2012 at 7:15
0

You can't access the variable names using an Array. What you could do is use objects or pass the variable names as a String:

var x = 7;
var y = 8;

function logVars(arr){
    for(var i = 0; i < arr.length; i++){
        alert(arr[i] + " = " + window[arr[i]]);
    }
}

logVars(["x","y"]);
2
  • "the function should be generic so I can't always assume that the scope is window." the OP says.
    – Joseph
    Apr 23, 2012 at 7:05
  • I know an array and and object works. But I want to save key strokes, see answer above. And I can't assume the scope is window. In fact I use the window scope as little as possible.
    – arpo
    Apr 23, 2012 at 7:15
0

I had a somewhat similar problem, but for different reasons.

The best solution I could find was:

MyArray = ["zero","one","two","three","four","five"]; 
MyArray.name="MyArray";

So if:

x=MyArray.name;

Then:

X=="MyArray"

Like I said, it suited my needs, but not sure HOW this will work for you. I feel silly that I even needed it, but I did.

-2

test this.

var variableA="valor01"; <br>
var variableB="valor02";

var NamevariableA=eval('("variableA")');<br>
var NamevariableB=eval('("variableB")');<br>

console.log(NamevariableA,NamevariableB);

atte. Manuel Retamozo Arrué

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.