Skip to content

Instantly share code, notes, and snippets.

@kevinwucodes
Created August 5, 2018 01:46
Show Gist options
  • Save kevinwucodes/cb543f2257acab14abebb0f693283a00 to your computer and use it in GitHub Desktop.
Save kevinwucodes/cb543f2257acab14abebb0f693283a00 to your computer and use it in GitHub Desktop.
Understanding JavaScript Functions

Today, I got stumped. Let's get unstumped.

While watching André Staltz's excellent Two Fundamental Abstractions talk, he shared something like this about 24 minutes into his talk:

const a = b => b(10)

a(x => console.log(x))

André said this was simple. But I had a brainfart and this completely stumped me. So I want to break this down and never get stumped like this again.

Substituting the above, we get this code mash:

(b => b(10))(x => console.log(x))

How do we break this down so we can understand what is going on?

We know that we can do this in JavaScript:

x => x + 1

This is just a function as evident by:

typeof (x => x + 1) === 'function' //true

If this is just a function, we should be able to give it some input and get some output back.

(x => x + 1)(2) //3
// ('the function') ('the input')

The first parenthesis set is our function. The second parenthesis set is our input. In my mind, I read this as (function)(input).

When we take our input of 2 and pass into this function, the 2 is passed into the left hand side of our x => x + 1 function. The left hand is expecting a single argument x. The right hand side of our function returns an expression of x + 1.

This means this function turns our input of 2 to 3 through the x + 1 transformation.

But what about b => b(10)? Well, lets break this down too.

(b => b(10))(x => console.log(x)) //??
//('the function') ('the function')

Wait, this is different than our (function)(input) example. This one is (function)(function). But the evaluation order is the same, so lets break that down too.

We know that functions are first class in JavaScript, so we can pass around functions as objects/arguments/inputs into other functions.

This means that our function x => console.log(x) is passed in to our b => b(10) function.

So lets continue breaking this down:

(b => b(10))(x => console.log(x))

Our function (x => console.log(x)) becomes b when we pass this function into (b => b(10))

(x => console.log(x))(10)

This looks familiar now, it's our friend, (function)(value)! We pass in our value of 10 into our function (x => console.log(x)).

Our final breakdown reveals:

console.log(10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment