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?
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();
Use console.log with a logical OR operator. This writes the arguments to the console.
const add = (x, y) => console.log(x, y) || x + y;
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