1

If one of my functions get an undefined parameter passed, I want to get the name of the variable outside the function so I can better troubleshoot the undefined variables. I.e.:

var myVar = document.getElementById("myTable").dataset.tablename;
//myVar: undefined

testVar(myVar);

testVar(param1) {
  if (!param1) console.log(passed parameter ??? undefined);
}

//??? shall be "myVar"
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Andreas
  • 47
  • 10
  • 3
    That's just not possible. The expression in the calling environment is evaluated, and all the target function gets is the value. You could generate an error and dump a stack trace out to the console. – Pointy Feb 01 '18 at 14:05
  • Use `typescript` to find such mistakes while programming. Thats much better then finding such stuff at runtime. And that pseudocode is ugly, just saying... – Jonas Wilms Feb 01 '18 at 14:13

1 Answers1

0

I don't think the thing you want to achieve is possible. You can look at the stack trace at debug time, but I will give you further information and ideas here:

  1. You could have a development policy in your team to name outside variables the same way as the parameters are at functions whenever possible. If you do so, this post will become useful.

  2. You might introduce a policy to pass objects to functions, like {name: 'John', age: 3} and then you will know the keys.

  3. You could create a Trackable prototype which would have a key and a value, like this:

function Trackable(name, value) { this.name = name; this.value = value; }

and pass trackables to functions when their names will be needed, thus you will call testVar(new Trackable('myVar', myVar)) and inside you will check param1.value against undefined and if it is undefined, then use the name in your report.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175