IT lexicon Programming Closure

Closure

Programming På svenska → Updated: 2026-07-30

Function that "captures" variables from its lexical scope. function counter() { let n = 0; return () => ++n; } — returned function has access to n even after parent returned. Standard in modern languages: JS, Python, Ruby, Go, Rust.

Practical use: callbacks with captured state, function factories, partial application, encapsulation without classes. JavaScript: enables IIFE pattern (Immediately Invoked Function Expression). Python: nested functions with nonlocal keyword for mutating captured vars. Memory consideration: closure holds reference to captured scope → potential memory leaks if captures large objects. Rust: closures are types (Fn, FnMut, FnOnce) — explicit ownership semantics. Static-typed-functional (Haskell, OCaml): closures are core construct, everything builds around them.

← Back to the lexicon