What is Closure in a Programing Language?

By Xah Lee. Date: . Last updated: .

What is Closure in a Programing Language?

In programing, it means a feature of a language such that a function/subroutine can maintain a state in a clean way. (For example, not using global variable.)

Here's example of closure in different languages.

Closure Example in JavaScript

// prepare to create a closure
function closure_context() {
    var x = 0;

    // f is closure here
    function f() {
        x += 1;
        return x;
    }

    return f;
}

// create a function that's closure
var closure = closure_context();

// demo of the function that can maintain state
console.log(closure()); // 1
console.log(closure()); // 2
console.log(closure()); // 3

〔➤see JavaScript: Closure

Closure Example in Python 3

# -*- coding: utf-8 -*-
# python 3

# closure example

# ff creates a variable context. It returns a function gg, which uses that context
def ff():
    xx = 0

    def gg():
        nonlocal xx
        xx = xx + 1
        return xx
    return gg

# myFun is a closure
myFun = ff()

print(myFun())                  # 1
print(myFun())                  # 2
print(myFun())                  # 3

〔➤see Python 3: Closure

〔➤see Python: Closure in Python 2

What's Closure in English?

Closure means a few things.

  1. In non-programing contexts, it means something is “closed”, or, a sense of completeness. For example: “I'm returning to my hometown for a sense of closure.”.
  2. In math, algebra, it means a property of a algebraic structure, namely: a function with input from elements of the set, whose result is always also a element in the set. (That is, we say, the set is “closed” under this function) For example, it's common to hear: “the addition operation is closed over integers.”. It means, adding 2 integers results in a integer. Division, for example, is not closed under integers. That is, dividing 2 integers may result in something that is not a integer. For example, fraction.
  3. In programing, it means a feature of a language such that a function/subroutine can maintain a state in a clean way. (For example, not using global variable.). And, a function using such a feature.

Closure is Computer Engineering Side-Effect, Not Math/Algorithm Concept

Closure, is a computer language feature. Note that it has no mathematical sense. It has no point in the science of algorithms.

First of all, a function, by having closure, ceases to be a function in a technical sense. Because, now it has side-effects. That is, the function's output, is not purely dependent on its arguments.

Secondly, if you think of functions as Interface, as in API, you can see that the so-called “closure” is no different from a function using global variables. No difference in interface. It's implementation detail.

Global Variable as a Crude Mechanism of Closure

Basically, if your language can define a function, and maintain a permanent internal variable inside, it's closure.

For example, if you define a global var, and your function access and or set that global var, your function will be able to maintain a state.

However, we all know global vars are bad because, for example, you have this big pool where everyone and every function accesses; it's hard to maintain and could be over-ridden by mistake.

So, a crude way to remedy this, is by following a convention, such that any global var whose name starts with a underscore is meant for special use. So, this way, you can have global vars _this , _that , _x, etc, and your function can access/set them. Now your function can maintain a state, while the typical problem with using global vars is avoided by a naming scheme.

Now, effectively, your function is said to have “closure”. Typically, that word is used when the language provide means to allow function to have a state without the above hackish method. However, it's no more complicated than that. In fact, it is effectively the only means to implement closure. If the language hides such global vars from user, and provide transparent ways when you create or access them inside your function without some naming scheme hack, that's closure.

Closure's Connection to Object Oriented Programing

Once a functional language's function's has states, that is, having closure, it is natural to extend the concept to become “objects” as in Object Oriented Programing.

When you start to program in a way of closures, that is, a function uses permanent internal variables to maintain states, and you have many functions like that, naturally, you might systematically explore this paradigm. Namely, instead of just one or two permanent internal variables, each of your function uses tens of such permanent internal vars. You might also start to define inner subroutines. Specifically, functions that lives only inside your function. You might apply these inner functions on your internal vars. This is the starting concept of so-called Object Oriented Programing. (For detail, see: What are OOP's Jargons and Complexities.)

Note: with respect to terminology, “closure” is a bad term. It spreads endless confusion and non-understanding. See:

Better Name: “Lexical Enclosure”

Tom Novelli suggested that “closure” should be named “enclosure”, or the full “lexical enclosure”. Excellent suggestion! See his blog at 〔TECH JARGON REFORM By Tom Novelli. @ http://tnovelli.net/ref/jargon-reform.html