In JavaScript, functions are not just functions, they are also closures. ALL functions are closures. What that means is that the function body has access to variables that are defined outside the function.
1let me = 'Bruce Wayne'
2function greetMe() {
3 console.log(`Hello, ${me}!`)
4}
5greetMe()
We can do this in JS, call the function without passing it an argument. But apparently, we can’t do this in other languages (which don’t have support for closures). In other languages we do it like this:
1function greetMe(me) {
2 console.log(`Hello, ${me}!`)
3}
4greetMe('Bruce Wayne')
The point of closures is that without them, you’ll be miserable in functional programming. You’ll have to manually pass a value as argument to the function, and to EVERY function inside that function
A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.
The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters. Note that the inner function cannot call the outer function’s arguments
object, however, even though it can call the outer function’s parameters directly.
You create a closure by adding a function inside another function.
A function with access to it’s own private variables. No other function knows about or can access these vars.
JavaScript variables can belong to the local or global scope. Private variables can be made possible with closures.
You can use the same variable name within different closure functions, and you can have as many closures as you want.
Inner function can access vars defined in outer function, as well as global vars. They won’t be accessible outside the clousre function though.
This is an example of lexical scoping: in JavaScript, the scope of a variable is defined by its location within the source code (it is apparent lexically) and nested functions have access to variables declared in their outer scope.
1function outerFunction() {
2
3 function innerFunction() {
4 someCount++;
5 console.log("Called" + someCount + " times");
6 }
7 return innerFunction;
8
9}
10
11counter1 = outerFunction();
12counter2 = outerFunction();
13
14counter1(); // Called 1 times
15counter2(); // Called 1 times
Closure is when a function remembers the variables around it even when that function is executed elsewhere