0

As I'm debugging, I'm consistently writing this bit of code:

a = 2;
// do some operation on variable a
console.log("The a variable is now " + a);

I wondered if I might create a function that shortens that process, like this,

function varlog(x) {
  var vartext = // this is what I don't know
  return "The " + vartext + " variable is now " + x;
}

var a = 2;
console.log(varlog(a));

Two questions,

  1. Is there a better way to solve this problem that I'm not seeing?
  2. If not, what should the vartext be to solve this problem?
  • 2
    Maybe this isn't possible, because what's being passed to the varlog function isn't "a," but "2." Put a different way, varlog doesn't have any idea what "a" is. – Adam Gosnell Dec 03 '21 at 19:07
  • 1
    This isn’t possible. Try something like `a = 2; b = 4; console.log({ a, b });` instead. This will log `Object { a: 2, b: 4 }`. – Sebastian Simon Dec 03 '21 at 19:09
  • 1
    See [Variable name as a string in Javascript](/q/4602141/4642212). – Sebastian Simon Dec 03 '21 at 19:11
  • 2
    Use a debugger that shows you all variables with their values. Logging something like `console.log("a = ", a)` should be *very* short-term and not something to rely upon extensively. – VLAZ Dec 03 '21 at 19:20

2 Answers2

3

You can use "Reflect" as below

function easyDebug(variable){

    let name = Reflect.ownKeys(variable)[0];
    let vals = JSON.stringify(variable[name]);
    console.log("The ( "+ name +" ) variable is now = ( " + vals +" )");
}

let a=5;
easyDebug({a});
//Will output
//The ( a ) variable is now = ( 5 )

let arr=[5,6,7];
easyDebug({arr});
//Will output
//The ( arr ) variable is now = ( [5,6,7] )

let obj={"key1":"val1","key2":"val2"};
easyDebug({obj});
//Will output
//The ( obj ) variable is now = ( {"key1":"val1","key2":"val2"} )

let obj2={obj};
easyDebug({obj2});
//Will output
//The ( obj2 ) variable is now = ( {"obj":{"key1":"val1","key2":"val2"}} )

let arrObj = [obj];
easyDebug({arrObj});
//Will output
//The ( arrObj ) variable is now = ( [{"key1":"val1","key2":"val2"}] )
  • 1
    Well, `Reflect` really isn’t necessary here; this is also not usually what `Reflect` is used for (it’s mostly used as the default action in [Proxies](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy)). This is no different from the other answer. – Sebastian Simon Dec 03 '21 at 20:01
2

By handing over a variable, the name is not known. the only part, where a variable is known, is to use short hand properties, where the variable name is now the property.

function varlog(x) {
    const [k, v] = Object.entries(x)[0];
    return `The ${k} variable is now ${v}`;
}

const a = 2;

console.log(varlog({ a })); // call with short hand property
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392