Skip to main content

Closures

Closures are functions that use variables from outside. These variables aren't their arguments and aren't made in their body.

What accounts to variables

In JavaScript, a variable can be a primitive, an object, or a function. An outside reference to any of these makes the function a closure.

Closure execution​

A function is a closure no matter when it runs. It can run at once, run via the caller, or be passed around.

Meaning of word closure​

Closure comes from the phrase close over which means something closes or cover something.

  • The eyelids closed over their eyes as they drifted off to sleep.
  • The lid closed over the box, securing its contents.
why the word closure

In JavaScript, the code block closes over all the data it needs around it.

It's a closed bundle of the function code plus the variables it needs to run on its own.

Lexical environment of closures​

Closures get their own lexical environment. When a closure is created, it gets its own map of variables and functions. It also gets a reference to the parent environment.

life of a closure

A closure stays alive as long as some other object references it.

This is just standard object management.