JS Shorts — Closures
Any function which uses a variable outside of it’s functional block within its lexical scope is an example of a Closure.

In theory, any inner function in JavaScript can access the variables defined in the outer function with the help of Closures.
In JavaScript, closures are created every time a function is created.

The above code is an example of the simplest closure. It gives the below output,
foo
In JavaScript, everything is under a global scope. Here, our function is defined on a global scope which is the outer scope for bar
, hence it has access to all the global variables.
In most cases, when we talk about closures we are normally referring to a nested function scenario. Let’s have a look,

The above code is a classic and well known example for closures, it gives the below output,
outerVariable
Notice how we are able to access the outerVariable
from innerFunction
since it has access to its lexical scope, ie: the scope where is has been declared.
Closures are commonly used for maintaining data privacy within a functional block and passing on common properties to several functions within a lexical scope.
For a more in depth write up, refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

— That’s all for today