Debugging Simple Arrow Functions More Efficientlyby@robertistok

# Debugging Simple Arrow Functions More Efficiently

July 27th, 2019

A simple simple arrow function can be used to debug simple arrow functions more efficiently. The function below is a quick way to do it using console.log to log the parameters. It is valid because of how logical operators work in JavaScript. We no longer have to convert our single line arrow function into a multi-line one. The technique is a game-changer when it comes to debugging arrow functions. Let's continue the discussion in the comments section to see what you think of this technique.

### Company Mentioned

Let's say we have the function below.

const complexFunction = (a, b) => a + b;

It works fine, but we seem to encounter a weird bug from time to time. So what's the first step we take in debugging? Yes, you got it, we will start by logging the function parameters.

In order to do that though, we would need to refactor our function to something like the one below. Including the curly brackets, writing the console.log and adding the return statement. It's a lot of extra steps, right?

const complexFunction = (a, b) => {
console.log("[DEBUG]", a, b);
return a + b;
}

But it does not have to be! If we just want to log the parameters, the version of the function below is a quick way to do it. We no longer have to convert our single line arrow function into a multi-line one.

const complexFunction = (a, b) =>  console.log("[DEBUG]", a, b) || a + b;

Just don't forget to remove the console.log once you've finished debugging.

It seems a little hacky though and why does this even work? The statement is valid because of how logical operators work in JavaScript.

"Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they will return a non-Boolean value"

Because console.log resolves tofalsy, the function will return the second part of it, which in our case is the a + b . Pretty neat, right?

Final words

Discovering this small trick was game-changer when it comes to debugging arrow functions more efficiently. What do you think of this technique? Did you know about this before? Let's continue the discussion in the comments section.

Thanks for reading, and subscribe to do not miss out on any of my future posts! 🙏

Robert is a full-stack web developer, currently working at Relatable. He loves to inspire people, explore new places, read great books, take inspiring pictures and learn new stuff all the time.