JavaScript (ES2015) crazy 1 liner

Can you tell whats going on in this 1 liner using Closures, Arrow functions, Destructing and Default values (to name a few)?

Our function

 const myString = ({msg = 'Print this' } = {}) => () => msg; 

When you run it the following happens:

myString // returns a function
myString() // returns a function
myString()() // returns 'Print this'

Lets break it down:

 const myString = () => {} 

Creating a 1 liner named function is simple with an Arrow function.

Lets introduce an argument:

 const myString = (hi) => {} 

Creates a function with a single argument.
Executing returns undefined.

const myString = (hi) => {return hi} 

Creates function with an argument and return it.
Executing with argument returns the argument (simples)

This can be simplified into below as Array functions return the last thing they run.

 const myString = (hi) => hi 

How about if our argument is an object with a default param set:

 const myString = ({msg = 'our message'}) =>  msg

Executing with an empty string (”) will print ‘our message’.
But without an argument will throw an error as the default is on the object property, we would need a default for our object (see below).

It could be updated to return an anonymous function

const myString = (msg = 'the inner string') => () => msg

This returns a Closure, which if executed returns our string.
i.e. myString()().

This is further expanded to use the default value within an argument (which has a default value)

const myString = ({msg = 'myMessage'} = {}) => () => msg 

This returns an anonymous function, returning a closure, returning a msg (phew).
Here we need the ‘= {}’ as our default param is inside an object, so we need the object covered. This allows execution without an argument.
i.e. myString()().

I find learning about the ES2015 features very interesting. There are more details about the above found at 2ality
Let me know if you read anything you dont agree with.

Leave a Reply