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"
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With