Skip to main content
Definition Website Computer and Technology

Closure

Subject: Computer and Technology noun /ˈkloʊ.ʒər/ 1 definition

  1. Definition (noun)

    Entry #85 · Updated

    A Closure is a function bundled together with references to its surrounding lexical environment, enabling it to access variables from an enclosing scope even after the outer function has returned. Unlike a stateless subroutine or a dynamically scoped routine that looks up free variables in the caller's execution context, a closure binds non-local references at creation time to the lexical scope in which it was defined. This pairing allows developers to encapsulate private state, preserve context across asynchronous callbacks, and construct higher-order abstractions such as function factories and curried helpers without relying on global variables or explicit object wrappers.

    Common Forms

    • Reference-Capturing Closures: Bind directly to variables in the enclosing scope—often promoting them from the call stack to heap-allocated cells—so updates made inside or outside the closure remain shared and persistent, as seen in JavaScript, Go, and Python (nonlocal).

    • Value-Capturing Closures: Copy the values of referenced outer variables into the closure's environment when it is constructed, isolating the closure from subsequent mutations in the enclosing scope, as in C++ [=] lambdas and PHP use bindings.

    • Ownership-Transfer (Move) Closures: Transfer ownership of captured bindings into the closure's own environment so it can safely outlive its originating stack frame or cross thread boundaries without garbage collection, as in Rust move closures.

    • Read-Only Closures: Restrict captured local variables to immutable or effectively final bindings that cannot be reassigned, preventing unintended side effects and race conditions in concurrent or functional code, as in Java lambdas.

    Example

    In a Node.js API gateway, a createRateLimiter(maxRequests) factory initializes a local requestCounts map and returns an inner middleware function that checks and increments each client IP's tally on incoming requests. Even after createRateLimiter returns and its stack frame is popped, the returned closure retains private access to requestCounts and maxRequests without exposing them in global state.