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.

Frequently asked questions

How does JavaScript handle closure?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Closures" snippet in JavaScript uses `function outer() {`.
Which code does the JavaScript example use?
The "Closures" snippet uses `function outer() {`, from the Functions section of the JavaScript cheat sheet.
Which stacks cover "closure" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Closures": 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.