Skip to content

Latest commit

 

History

History
39 lines (29 loc) · 1.42 KB

log-a-variable-in-an-arrow-function.md

File metadata and controls

39 lines (29 loc) · 1.42 KB
title category date topics
Log a variable in an arrow function
Trick
2021-02-25 11:57:00 +7
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

See also