What Makes A Closure? 95% Programmers May be Misunderstood.

李白字一日
2 min readMar 27, 2021

It seems most people don’t clearly understand what is a closure.

It also confuses me.

I was told that functions are closures.

I don’t quite agree with that, but such claims are everywhere, I don’t know if it is right and wrong.

In this post, I will try to give reasons what I think a closure really is.

WIKI

According to WIKI

In programming languages, a closure, also lexical closure or function closure, is a technique for implementing lexically scoped name binding in a language with first-class functions. Operationally, a closure is a record storing a function[a] together with an environment

There are two premisses:

  1. scoped name binding (environmental data)
  2. first-class functions (operations)

In brief, a closure in effect is an operation on some environment/data and result in the environment. So there is at least one function and one variable to consist one closure.

A single function or a single variable doesn’t make a closure.

To make a closure, a program must have the operations (functions) on that environment(normal a variable) and normally result in that variable(means variable must be changed).

So the following code doesn’t make a closure (in js)

It only references the passed variables, and produces a new result. That result won’t change anything.

And this one does:

Because the environment(variable i and step) is changed, the operation (anonymous function) will change the environment every time it is executed.

A closure means that the result is closed to one set/range, normally a variable or an array in computer.

To this example we can consider the sets to be the integer sets (i is one set, step is another).

And there are two closure relationships:

Why I think an operation should be closed by the environment.

Because in mathematics wiki, it writes:

In mathematics, a set is closed under an operation if performing that operation on members of the set always produces a member of that set. For example, the positive integers are closed under addition, but not under subtraction: 1 − 2 is not a positive integer even though both 1 and 2 are positive integers. Another example is the set containing only zero, which is closed under addition, subtraction and multiplication (because 0 + 0 = 0, 0 − 0 = 0, and 0 × 0 = 0).

The above is what I consider what a closure is, What do you think?

Originally published at https://dev.to on March 27, 2021.

--

--