0

I'm reading a Javascript (ES6) book, and in Chapter 7 (Scope) there's an obscure example (at least for me as a beginner) that I can't wrap my head around.

const f = (function() {
            let count = 0;
            return function() {
                return `I have been called ${++count} time(s).`;
                }
            })();

f(); // "I have been called 1 time(s)."
f(); // "I have been called 2 time(s)."
//...

So, the count variable is initialized at 0 but, why is the value of it still "alive" in subsequent calls to the f function? is the first unnamed function still valid behind the scenes somewhere in memory or anything like it?

rockdudex
  • 13
  • 3
  • 1
    the function returned by the IIFE is in the same scope as count – Jaromanda X Nov 21 '16 at 03:46
  • Not sure that duplicate answers your question so let's try a comment. A scope is where you define "bindings" (variables and functions) in JS. Global is a scope, each function's execution creates a scope, the parameter block of each function and each for loop is also a scope, etc. An execution may end but its scope, like an object, may lives on if it is still referenced by some code. All code and all data lives in memory so yes, it is still in the memory. – Sheepy Nov 21 '16 at 04:22

0 Answers0