0

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
Bram
  • 669
  • 3
  • 12
  • 25
  • 1
    *Every* function is a closure. Just most are not very interesting, so most talk about closures is about a function that returns a function. – VLAZ Mar 21 '22 at 17:48
  • It's about whether a function does something that affects the "world" outside of its scope. That's usually via a `return`, but it can also happen because a function changes something in an enclosing scope. – Pointy Mar 21 '22 at 17:49
  • 2
    They both increment `a`. And they always do it right after printing its value. The *difference* is that in the second example you invoke the same `childFunc` twice and operate on the same `a` value twice, whereas in the first example you create two different `childFunc`s and invoke each once, each with its own value of `a`. Since the updated value of `a` is only observed the second time `childFunc` is invoked, invoking it only once will never observe that updated value. – David Mar 21 '22 at 17:54

0 Answers0