Closures : what senior developers won’t tell you

“Understanding closures is like when Neo sees the Matrix for the first time.”

Closures are hype. Knowing how to recognize them is pretty well valued in the developer’s game. And that’s why the secret is well kept. But in reality : closures are everywhere. You’ve already used them without knowing it.

In this article we’re going to explain how to precisely recognize a closure. No more frustration, and finally the “aha moment” that you were looking for.

Let’s take a look at the boring definition first :

Closure is when a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope.

Here we only have to remember two main points. I call them the binding and the export.

The binding 🔗

The binding

Here we have created one function (bar) nested in an other function (foo). The nested one access to a variable (a) of its lexical scope. Now, the function bar is able to “remember and access its lexical scope”. We can say that the scope of bar is bind to the scope of foo.

The lexical scope of a function is the scope in which the function is nested. For example the lexical scope of the function bar is the function foo.

Yes that’s the first part of the definition. So is it technically a closure ?

Still not, we’re missing the last part.

The export ✈️

The export

Look at how bar is being passed as the return value of the foo function. And look at how we assign this returning value to the variable baz.

The function bar is now exported, man. We can “execute it outside its lexical scope”. In other words, we can use the bar function directly without passing by the foo function.

It’s ready ! 🍰

The function bar still has a reference to the function foo scope, and that reference is called closure.

Our closure is now totally finished and ready to use everywhere in our code.

“Whatever facility we use to transport an inner function outside of its lexical scope, it will maintain a scope reference to where it was originally declared, and wherever we execute it, that closure will be exercised.”