Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 491
Max Koretskyi Avatar asked Dec 15 '22 09:12

Max Koretskyi


2 Answers

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();
like image 162
lleaff Avatar answered Dec 23 '22 17:12

lleaff


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;
like image 24
Cory House Avatar answered Dec 23 '22 19:12

Cory House