How to log both variable and its name?

Viewed 327

I find myself typing this repeatedly for debugging in my code. Is there a way to create a function for this?

var abc = 1
console.log("abc = "+abc);

var xyz = 2;
console.log("xyz = "+xyz);

I would like to create a function like this:

logVar = function(input){
  console.log(input.name()+" = "+input);
}

Is there a way to do this?

logVar(abc) should return "abc = 1"

logVar(xyz) should return "xyz = 2"

4 Answers

You have to enclose you var in a object to get its name as a key:

var myVar = 'John Doe';

console.log({myVar}); // result {"myVar": "John Doe"}

You can create an object from your variable which you pass into logVar.Then, in your function, you can use Object.entires to get the name of the variable and the value of the variable.

See example below:

var logVar = function (input) {
    var [[name, val]] = Object.entries(input);
    console.log(name, "=", val);
}

var abc = 1;
var xyz = 2;

logVar({abc}); // abc = 1
logVar({xyz}); // xyz = 2

Though this is not a proper solution, you can loop over the window object, but you can get other identifiers as well which hold the same value as the passed in argument. This only works in global scope & not while in function scope.

var ident = "wowowowow";
console.log(getIdentifierName(ident));

function getIdentifierName(identifier) {
  for (var prop in window) {
    if (window[prop] === identifier) {
      console.log(identifier);
    }
  }
}

This should work:

var abc = 1;
logVar = function(input) {
  console.log(input);
}
logVar({
  abc
});

The output should be something like : { abc: 1 }

Related