What is a Closure in JavaScript?

Closure is one of important concept in JavaScript. It is widely discussed and still confused concept. Let's understand what the closure is.

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.In other words, a closure gives you access to an outer function’s scope from an inner function.

Before we dive into closures, let’s first understand the lexical scope.

What is a Lexical Scope?

A lexical scope or static scope in JavaScript refers to the accessibility of the variables, functions, and objects based on their physical location in the source code. For example:

Here the inner function can access the variables defined in its own scope, the outer function’s scope, and the global scope. And the outer function can access the variable defined in its own scope and the global scope. Hence we ca say that inner function is surrounded by the lexical scope of outer function which is, in turn, surrounded by the global scope. That’s why the inner function can access the variables defined in outer function and the global scope.

Closure

Consider the following code example:

Running this code has exactly the same effect as the previous example. What's different (and interesting) is that the displayName() inner function is returned from the outer function before being executed.

The reason is that functions in JavaScript form closures. 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.

When to use Closure?

Closure is useful in hiding implementation detail in JavaScript. In other words, it can be useful to create private variables or functions.The following example shows how to create private functions & variable.

In the above example, increment(), decrement() and value() becomes public function because they are included in the return object, whereas changeBy() function becomes private function because it is not returned and only used internally by increment() and decrement().

Conclusion?

So we have learned what closures are and how they really work. Closures are fundamental concepts of JavaScript that every JavaScript developer should understand. Having a good knowledge of these concepts will help you to become a much more effective and better JavaScript developer.

That's all for now. Thank you for reading and I hope this post will be helpful :)