DEV Community

Cover image for Quick Tip to Console-Logging Arrow Functions
Kai
Kai

Posted on

Quick Tip to Console-Logging Arrow Functions

(skip to TL;DR)

Guess what? My first Tweet "blew up"! Well, actually not really, but compared to my normal response rate of two (thanks Arden and David), it was insane.

A picture of my Tweet which will be further described in the next paragraph of this post
I just shared a quick-tip I, myself, learned on Twitter only a few months ago. It was about how you can wrap curly braces around a variable in your console.log statements to transform it to an object and have the variable name automatically prefixed as the object's key.

const foo = 'bar', bar = 42;
console.log({ foo, bar }); // Object { foo: "bar", bar: 42 }
Enter fullscreen mode Exit fullscreen mode

This helps to track the values in the console output easily. It basically ditches the need to add stuff like 'foo: ', foo.

Console Log in One Line Arrow Functions

The problem with one line arrow functions is, that if you wanna debug them with console.log1, it's fairly annoying since you have to add curly braces and a return statement to it.
Let's take the following function:

const foo = (bar) => bar.do();
Enter fullscreen mode Exit fullscreen mode

If you want to see what's in bar, you commonly have to do something like this:

const foo = (bar) => {
 console.log('bar: ', bar);
 return bar.do();
}
Enter fullscreen mode Exit fullscreen mode

Now check this 🧙:

const foo = (bar) => console.log({bar}) || bar.do();
Enter fullscreen mode Exit fullscreen mode

We utilise that console.log always returns undefined (being falsey) and thus the second bit of the or operator gets executed.
No more annoying line breaks and stuff! Just add console.log() || in front of your function body, and you are good to go.

TL;DR

const foo = (bar) => console.log({bar}) || bar.do();
Enter fullscreen mode Exit fullscreen mode

  1. Yeah, I know, you shouldn't debug with console.log hurr durr. We still do it all the time. 

Top comments (0)