COOKIES! This blog uses cookies!
I am completely out of control of cookies here, otherwise I would have disabled them (it is controlled by the platform).
If you don't like cookies and being tracked please leave this blog immediately.

Tuesday, 15 September 2015

Explaining closure pattern name

Live and learn. Indeed.

I'm currently reading a book about Scala and found that "closure" "design pattern" which I've been using in JavaScript for ages is actually from functional programming world, and this closure is not a whole thing, but a variable closing so called "open term".

Imagine the function:
function myFunc(a) {
  return a + b
}

The "a" variable here is a "bound variable", and it makes sense in context of myFunc. The "b" variable is a "free variable" and it is senseless in this context. The "a + b" expression here is an "open term". On the other hand if we replace the expression in myFunc with something like "a + 2" it will be a "closed term".

The name "closure" arises from the act of "closing" the function literal with the open term(s) by "capturing" bindings of its free variables.

var b = 2 //this b variable is actually a closure!
function myFunc(a) {
  return a + b
}

That's it. This variable is the "closure". And the thing is the "function literal" with the "open term".