← #38 Return an object in an arrow function quickly
#39

Log a variable in an arrow function

Topics: JavaScript

Have you ever had to debug an 1 line arrow function using console.log? It usually requires us to switch to a multiple lines version such as:

const formatYmd = date => {
console.log(date.toISOString());
return date.toISOString().slice(0, 10);
};

You can get rid of that conversion by using the || operator. It works because console.log() returns undefined, so the || will enforce the function to evaluate and return the right side which is our actual function.

const formatYmd = date => console.log(date.toISOString()) || date.toISOString().slice(0, 10);

formatYmd(new Date());
// Print something like `2021-02-25T04:52:39.720Z` in the Console

There is another, less known tip which uses the comma operator:

const formatYmd = date => (console.log(...), date.toISOString().slice(0, 10));

You will find more useful 1 line-of-code functions on 1 LOC

More

Fix a typo or suggest an improvement
#40 Use the strict equality operator when comparing variables