What are JavaScript closures?

It is a JavaScript feature that allows a function to access its outer function scope. Sounds complicated?

We can use this feature when we have nested functions like this:

Image for post

A simple example of closures

As you can see the function sayAge has access to the variable age which is in the outer function scope. This is a special feature of JavaScript and we can use it in some situations that I will explain.

A common trick with closures

If we return a function from another one we can mutate the outer function variables by using the closure feature. For example:

Image for post

Changing the outer function’s variable

JavaScript closures are as simple as this example but I didn’t understand them till I found a practical usage.

#closure #web-development #frontend #javascript #programming

JavaScript closure in plain language and one practical real-world example
1.25 GEEK