JavaScript Closures

Lukas Polak
1 min readSep 4, 2020

--

The closure is a function that remembers the variables from the place where it was defined, regardless of where it will be executed later. In other words, a closure is a function bundled with its lexical scope. Callbacks, event handlers, higher-order functions can access variables from the outer scope thanks to that. The closure is created at runtime during the function creation, and the JavaScript engine needs to keep the variable from the outer function available until the inner function has been called. In some cases, closures can be referred as a “nested functions” or “ghost”/”memory” of the past function calls.

Function from the inner scope has access to variables defined in the outer scope because of the lexical (static) scoping. Even function executed outside of its lexical scope can access the variables defined in its lexical scope.

How can you identify a closure? If a function uses a variable that is not defined inside the function scope, it is probably a closure.

Originally published at https://dev.to on September 4, 2020.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response