es6 arrow functions debugger statement

If I have a function like that:

param => params + 1

and I need to put a debugger statement inside the function’s body. Is adding parenthesis like this:

param => { debugger; return params + 1 }

the only option?

Answer

From the MDN article on arrow functions:

(param1, param2, …, paramN) => { statements }
(param1, param2, …, paramN) => expression

You can see that the brace-less syntax requires the code on the right of the arrow to be an expression, which is an (unfortunate) distinction made by the language itself.

Since debugger is a statement, using it anywhere an expression is expected is a syntax error. One thing you could to to work around this is to transform your debugger statement in an expression which you trick JavaScript into evaluating but not returning, e.g.:

function debug(args) {
     debugger;
     return true;
}

params => debug() && params + 1

// or

params => console.log(params) || params + 1

The way this works is that because of the way logical operators function in JavaScript, this is true:

truthyA && B  === B

falsyA || B === B

When chaining logical operators, JavaScript evaluates sub-expressions left to right and then act depending on their boolean equivalent. That’s why you’ll sometimes see && used in place of if statements:

 if (smth) doStuff();
 // is equivalent to:
 smth && doStuff();

Leave a Reply

Your email address will not be published. Required fields are marked *