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.
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 }
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.log
1, 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();
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();
}
Now check this 🧙:
const foo = (bar) => console.log({bar}) || bar.do();
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();
-
Yeah, I know, you shouldn't debug with
console.log
hurr durr. We still do it all the time. ↩
Top comments (0)