# Closure

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

**Field:** Software Development  
**Category:** Programming Paradigms  
**Also known as:** Closures, Lexical Closure

## Think of it like

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

## 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

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

## 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.

## Why it matters

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

## 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.

## Three principles

- **Remembers its birthplace.** Keeps the outer variables.
- **Lives on.** After the outer code ends.
- **Private state.** Without a class.

## Related terms

- [Scope](https://learn.benibix.com/term/development/scope)
- [Function](https://learn.benibix.com/term/development/function)
- [Lambda Function](https://learn.benibix.com/term/development/lambda)
- [Callback Function](https://learn.benibix.com/term/development/callback)

## Told apart from

- [Lambda vs Closure](https://learn.benibix.com/compare/lambda-vs-closure): A lambda is a short function with no name. A closure is a function that keeps the variables from where it was made. A lambda can be a closure, but the two words mean different things.

---

Source: https://learn.benibix.com/term/development/closure
Author: Behnia Zarei (a developer in Vienna, Austria, who builds and teaches data, AI and business intelligence at BENIBIX)
Publisher: BENIBIX Learn (https://learn.benibix.com/)
Last updated: 2026-11-17
Licence: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Quote freely with attribution.
