0

Why is the first function (AKA parent function) only called once in this javascript closure code?

The parent function is called each time right? I believe that the console.log in the parent function should work each time, but it doesn't.

    const Parent = (() => {
    let value = 0;
    console.log(`initial value: ${value}`);
        return () => {
          value += 1;
          console.log(`${value}`);
      };
   })();

   Parent(); //initial value: 0 , 1
   parent(); // 1
   parent(); // 2
   parent(); // 3
Joundill
  • 5,418
  • 11
  • 31
  • 47
Ritalin
  • 11
  • 1
  • Your IIFE runs the code on its top level - the `let value = 0` etc - once, because that's how IIFEs work. Here, it's not doing much except providing a private closure for the `value` variable, an equivalent would be `let value = 0; const Parent = () => { value += 1; console.log(value); }` – CertainPerformance Jan 23 '22 at 03:37
  • let me get this straight , you are telling me that the parent function doesn't make any change and just makes variables private and of course that's why i see the console.log once right ? thanks a lot . – Ritalin Jan 23 '22 at 05:18

0 Answers0