Closure

2 snippets across 2 stacks — JavaScript, Python

JSJavaScript

Closures

JS · Functions
syntax
function outer() {
  let state = value;
  return function inner() { /* access state */ };
}
example
function createCounter(initial = 0) {
  let count = initial;
  return {
    increment() { return ++count; },
    decrement() { return --count; },
    value()     { return count; },
  };
}
const counter = createCounter(10);
console.log(counter.increment()); // 11
console.log(counter.increment()); // 12
console.log(counter.value());     // 12

Note A closure is a function that retains access to its outer scope's variables even after the outer function has returned. Fundamental for data privacy and stateful functions.

PYPython

Closures

PY · Functions
syntax
def outer():
    captured = value
    def inner():
        return captured
    return inner
example
def make_multiplier(factor: int):
    def multiply(n: int) -> int:
        return n * factor
    return multiply

double = make_multiplier(2)
triple = make_multiplier(3)
print(double(10), triple(10))
output
20 30

Note The inner function captures the enclosing variable by reference, not by value. See Common Mistakes for the late-binding closure gotcha.