Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly does "closure" refer to in JavaScript?

I understand what closures are, but I am having some trouble grokking exactly what the term closure refers to. I have seen the term used in many websites, but rarely do they agree on the actual definition of it.

  • Is it the variables that are kept on the stack frame?
  • Is it the function that is being returned?
  • Is it the scope of the outer function?
  • Is it the scope of the inner (returned) function?
  • Is it maybe the concept of keeping the variables on the stack-frame after returning the function?

Can someone tell me exactly to what closure refers to?

like image 977
Andreas Grech Avatar asked Nov 26 '09 06:11

Andreas Grech


People also ask

What does closure refer to?

1 : an act of closing : the condition of being closed closure of the eyelids business closures the closure of the factory. 2 : an often comforting or satisfying sense of finality victims needing closure also : something (such as a satisfying ending) that provides such a sense.

What is a closure in code?

A closure is a programming technique that allows variables outside of the scope of a function to be accessed. Usually, a closure is created when a function is defined in another function, allowing the inner function to access variables in the outer one.


1 Answers

From JavaScript Closures

Two one-sentence summaries:

A closure is the local variables for a function - kept alive after the function has returned, or

A closure is a stack-frame which is not deallocated when the function returns. (as if a 'stack-frame' were malloc'ed instead of being on the stack!)

A very good article on closures

Javascript Closures

A "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).

The simple explanation of a Closure is that ECMAScript allows inner functions; function definitions and function expressions that are inside the function bodies of other functions. And that those inner functions are allowed access to all of the local variables, parameters and declared inner functions within their outer function(s). A closure is formed when one of those inner functions is made accessible outside of the function in which it was contained, so that it may be executed after the outer function has returned. At which point it still has access to the local variables, parameters and inner function declarations of its outer function. Those local variables, parameter and function declarations (initially) have the values that they had when the outer function returned and may be interacted with by the inner function.

A good example over here

JavaScript, time to grok closures

like image 133
rahul Avatar answered Oct 01 '22 01:10

rahul