What is Closure in Javascript?

What are closures?

Closures are functions that have access to the variables that are present in their scope chain even if the outer function ceases to exist. In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

Example

function display() {    var name = 'John';    function displayName() {      console.log(name);    }    displayName(); } display();

Explanation

1.  var name = 'John';  // name is a local variable created by display().

2.  displayName() is the inner function, a closure

3.  console.log(name); // use variable declared in the parent function

Benefits of closure function

1. Variables in closures can help you maintain a state that you can use later. 2. They provide data encapsulation. 3. They help remove redundant code. 4. They help maintain modular code.

Conclusion

1. The scope rules the accessibility of variables. There can be a function or a block scope. 2. The lexical scope allows a function scope to access statically the variables from the outer scopes. 3. Finally, a closure is a function that captures variables from its  lexical scope.

Conclusion

4. In simple words, the closure remembers the variables from the place where it is defined, no matter where it is executed. 5. Closures allow event handlers, callbacks to capture variables. They're  used in functional programming.

That's it.

I hope you enjoyed the article and if you found this useful, then please share it with your friends and colleagues. I write tech articles that helps developer to boost their productivity and life hacks. Read more for cool stuff.