0

In C++ we can write a preprocessor macro like this:

#define DEBUG(x) cout << '>' << #x << ':' << x << endl;
int a=1;
DEBUG(a) //prints "a:1"

I tried to do a similar thing in javascript

var DEBUG= function(name){
  return function() {
      console.log(name+": ",eval(name))
  }
}
{
    let a=1;
    DEBUG('a')() //a is undefined
}

I was wondering if there was any way to "inline" functions or otherwise do some clever thing with closures which allows DEBUG to be evaluated in the calling scope. I know I could just call DEBUG('a',a) but that wouldn't be as fun ;)

4
  • but that wouldn't be as fun - but it's the only way Commented Oct 12, 2017 at 2:05
  • To summarize tadman’s answer: console.log({ a }) Commented Oct 12, 2017 at 2:10
  • 2
    All you could do is eval(debug('a')), where eval is called in the scope where the variable is available. Or you just do the same thing as in C++ and use an actual preprocessor which does macro expansion Commented Oct 12, 2017 at 2:10
  • @Bergi having debug return an eval string is pretty clever, I hadn't thought of that. Commented Oct 12, 2017 at 2:22

1 Answer 1

1

There's really no need for such a heavy-handed approach. You can always do this:

function debug(a) {
  console.log(a);
}

Or you can define an empty version of same with no functionality to disable it in certain run modes.

To use it is easy:

debug({ a: a, b: b });

With ES6 you can do this even more concisely:

debug({ a, b });

Couldn't be easier.

Your idea of using eval is going to fail because a is a variable that only exists inside of that specific scope due to the let declaration. That means the other function has no ability to access it.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, that's pretty much exactly what I was looking for. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.