I have been playing around with closures a little bit and I have a difficult time understanding what's the difference between lexical scoping and closures.
In the examples below both child functions are able to reach the a
variable thanks to lexical scoping. Now I wonder where exactly is the closure created in the second example? Is it because of the childFunc()
being returned directly, or is it because of childFunc()
being stored in a seperate child
variable before being exectuted?
Example 1: No closure
function parentFunc() {
let a = 10;
function childFunc() {
console.log(`hey from child func Mr. ${a}`);
a++;
}
childFunc();
}
console.dir(parentFunc) //closure not part of the Scopes
parentFunc() //doesn't increment a
parentFunc()
Example 2: Closure
function parentFunc() {
let a = 10;
return function childFunc() {
console.log(`hey from child func Mr. ${a}`);
a++;
}
}
const child = parentFunc()
child(); // increments a
child();
console.dir(parentFunc) //closure is part of the scopes