From every definition I have looked up, closure is when a function is created or declared from within another function. Examples are plentiful across blogs and websites of this happening. But what about when the function is declared outside of another function, but called then called from within a function? For example:
const add = (x,y) => {
return x + y;
};
const double = num => {
return add(num,num)
};
let a = double(6);/*?*/
Does add(num, num) create closure? If so, please help me understand why.
Closures are a product of lexical scope.
A closure is the combination of a function and the lexical environment within which that function was declared.
You must define a function within another one to create a closure.
What you do in your example is simply call a function that calls another and uses its return value. At no point can the double function access the scope of the add function: their scopes are distinct.
Here is a classical example of JavaScript closure
var makeAdder = function(x) {
return function(y) {
return x + y;
};
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
console.log(add5(2)); // 7
console.log(add10(2)); // 12
In both cases, the functions returned by makeAdder, "remember" the outer scope in which the were created (the scope created by the makeAdder function).
Anything that was in scope of the outer function was also in scope for the inner function, and it remains so when the inner function is returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With