Skip the Intermediate, Clean ES6

Use anonymous functions to make 2 lines of code into 1. Declare a variable and do something with it all in 1 step.

Jen
2 min readMar 15, 2021

It has bothered me for a while that something like this:

const d = new Date()//today's date (Intermediate I don't care about)
d.setDate(d.getDate()- 2);// Method to get date for 2 days ago
d // What I actually care about: The Date instance for 2 days ago.

Requires me to use 2 lines. First I have to declare an instance representing today’s date. Then on a separate line. I have to call the method. And then finally, I can use d as an instance of the date 2 days ago. Well, no more…

Simplify:

const date=((d)=>{d.setDate(d.getDate()- 2); return d;})(new Date())

What I did was declare and call an anonymous function in 1 line, passing in the instance to be modified as the argument.

Here’s another example using regex:

When extracting a match with regex, it either returns an array (if there is a match) or null (if no match). But often what you actually care about is extracting the matched substring, which requires indexing into the array.

Something like this though: const m = "hello12".match(/(\d\d)/[1]

Errors if there is no match, since string.match(/(\d\d)/) returns null and you can’t do null[1] .

However, for those used to doing lines like this:

const y = fetchValue(x) || default_value ,

it feels silly to have to use 2 lines to account for a function returning null :

let m = "hello12".match(/(\d\d);
m = m? m[1] || default_value;

or unnecessarily expensive 1 lines like this:

const m = "hello12".match(/(\d\d)? "hello12".match(/(\d\d)|| null; 

Instead, Do this:

const m = ((x)=> x.match(/(\d\d))("hello12");

How it works:

Declare anonymous function: ()=>{} .

Use variables within the scope of the anonymous function:

(x)=>{return x+1;}

Call anonymous function by wrapping it in parentheses and pass it an argument: ((x)=>{x+1})(arg)

Now that’s one pet peeve solved for the day. Enjoy!

--

--