Skip to content
BENIBIX Learn

Closure

Development🧭 Programming ParadigmsFunctional Programming

Also known as Closures, Lexical Closure

A function that keeps the variables near it. It still has them later.

Think of it like

Think of it like a backpack. The function takes it along and keeps what was packed inside.

Example

Emma makes a counter. She calls it twice, and it says 2, because it kept its own count between calls.

Why it matters

Closures sit behind callbacks, event handlers and React hooks. They explain why a function sees a value you thought was gone.

Definition

A closure is a function that keeps the variables from the place where it was made. The outer function may finish, but the inner one can still read and change them. A counter is the classic example: each call adds one to a number only the counter can see. Many languages use closures to keep private state without a class. JavaScript and Python both use them a lot.

Example code

python
def counter():
    n = 0
    def step():
        nonlocal n
        n += 1
        return n
    return step

c = counter()
c()
print(c())  # 2
step keeps n alive after counter has finished.

Common mistake

Making closures in a loop and expecting each to keep its own loop value. In some languages they all share the last one.

Key takeaways

  1. 1
    Remembers its birthplace. Keeps the outer variables.
  2. 2
    Lives on. After the outer code ends.
  3. 3
    Private state. Without a class.

Compare