Skip to main content

Closure

What is a closure in JavaScript? Can you provide an example?

Ans: A closure is a function that has access to its parent function's scope, even after the parent function has returned. An example of a closure in JavaScript is when you create a function that returns another function that references a variable in the parent function's scope.

  • variable stays around even after function returns
  • when there's an inner function and an outer function
  • a closure can make the creation of very similar functions efficient
  • Closure functions can even modify bound variables in the background
  • A closure is a function that has access to its outer function scope even after the outer function has returned. This means a closure can remember and access variables and arguments of its outer function even after the function has finished.
  • A closure is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time the closure was created.
  • a stateful function
  • commonly used to give objects data privacy
function getAsyncData(callback){
setTimeout(function(){
callback("Here is the data")
},3000)
}

var waitForAsyncData = new Promise(function(resolve, resolve){
setTimeout(function(){
resolve("gimme the light";
})
});

Closure Scope Chain

For every closure we have three scopes:

  • Local Scope ( Own scope)
  • Outer Functions Scope
  • Global Scope

  1. Closures are useful because they let you associate some data (the lexical environment) with a function that operates on that data. This has obvious parallels to object-oriented programming, where objects allow us to associate some data (the object's properties) with one or more methods.

  2. Consequently, you can use a closure anywhere that you might normally use an object with only a single method.

  3. Situations where you might want to do this are particularly common on the web. Much of the code we write in front-end JavaScript is event-based — we define some behavior, then attach it to an event that is triggered by the user (such as a click or a keypress). Our code is generally attached as a callback: a single function which is executed in response to the event.