What is Closure in Programing Language

By Xah Lee. Date: . Last updated: .

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
const gg = (() => {
  let x = 0;
  const ff = (() => (x += 1));
  return ff; // the returned ff is a closure

// create a function that's closure
const cc = gg();

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

/* [
when gg is called, it has a local variable x.
when gg exits, the local variable x does not go away, because it is still used.
It is used by the inner function f, which is returned.
] */

[see JavaScript: Closure]

Closure Example in Python 3

# python 3

# closure example

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

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

# cc is a closure
cc = gg()

print(cc() == 1) # True
print(cc() == 2) # True
print(cc() == 3) # True

[see Python 3: Closure]

[see Python: Closure in Python 2]

Closure Example in Golang

package main

import "fmt"

// return a closure
func make_add_1() func(int) int {
	var i = 0

	var gg = func(x int) int {
		i += x
		return i

	// the returned function gg, is called a “closure”
	return gg

func main() {
	var f = make_add_1()

	fmt.Println(f(1)) // 1
	fmt.Println(f(1)) // 2
	fmt.Println(f(1)) // 3


Golang: Closure

What is Closure in English?

In computer science, it means:

A feature of a language such that the local variables of a function/subroutine do not necessarily go away when the function exits. The variables remain and maintain their values if the variables are still used (for example, when the variable is used by a inner function that is returned).

In programing, it practically means:

A function/subroutine that maintains its own variable state in a clean way (this is like using global variables, except they are not global variables.)

Outside of computer science, “closure” also means:

  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.

Closure is Programing Language Design Concept, 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 Alternative to 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 naming convention. For example, create global variables whose whose name starts with a dollar sign, followed by the function name, followed by a random string. e.g. $getSession__ttlqtpvz8i. Now your function getSession can maintain a state, while the typical problem with using global vars is avoided.

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 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!

Different Meaning of Closure: Language Feature vs API

when we think of closure, we think of function with state. however, in some tech sense, closure is just a feature of f of the lang, not necessarily having a state. So, emacs lisp calls all lexical scoped function closure, even if it's just a normal function.

emacs lisp closure 2018-07-23
emacs lisp closure 2018-07-23

the thing to note here is that, often, a tech jargon have entirely different meanings. e.g. closure as language feature in lang design sense is entirely different from closure as function with state from programer perspective.

Programing Language Design Problem, Conflict of Interest of Closure, and How to Ban Closure

closure (function with state) should be ban'd. Because, it is no longer a function in the math sense. Side effect becomes the point. It's, a abomination. From a lang design feature point of view, closure is watered down form of class in Object Oriented Programing.

in programing language design, you want simplicity principle. e.g. since subroutine take value and return value, it should consider λ as value, and able to take λ or return λ. No exceptions. Simplicity!

But now you got a problem, when some coder write inner λ2 that uses outer λ1 var and return λ2, a closure! thus creating side effect. So, how to resolve this problem?

One naive solution, is to still allow λ as input/output, but ban λ with side effect. usually, you can't just ban side effect λ. first your language must to be to detect it. The solution of ban side effect λ usually comes in other forms, e.g. language with typed var.

Ban Nested Closure?

now let's consider nested closure…

when closure is nested, you have realm within a realm.

by the way, did you know, realm is a technical jargon in ECMA-262? #JavaScript

JavaScript spec realm 2018-07-24 9c3c2
JavaScript spec realm 2018-07-24

Programing Jargons