How to log both variable and its name?

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

Tags:

Javascript