Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log both variable and its name? [duplicate]

Tags:

javascript

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"

like image 406
Wes Tomer Avatar asked Jun 24 '19 13:06

Wes Tomer


People also ask

Can you have duplicate variable names in a project?

It is legal for 2 variables in different scope to have same name. Please DO read §6.3. Scope of a Declaration from JLS. Below are few of the statement from that section.

Can you have two variables with the same name Javascript?

It's not possible, an if statement has no special scope, so you can't have two variables with the same name within the same scope and access both, the latter will overwrite the former, so they should have different names.

Can you have duplicate variable names in a project C#?

Essentially, it's not allowed because, in C#, their scopes actually do overlap. edit: Just to clarify, C#'s scope is resolved at the block level, not line-by-line.

Can the same variable name be used in more than one function?

Yes you can, as long as you don't forget the var keyword : the scope of a variable is either the function in which it is declared or the global scope.


2 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"}
like image 186
Mosè Raguzzini Avatar answered Oct 25 '22 16:10

Mosè Raguzzini


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
like image 21
Nick Parsons Avatar answered Oct 25 '22 15:10

Nick Parsons