0

Can someone explain me way the counter are called one time inside this function

let uniqueInteger = (function() {
  let counter = 0;

  function f() {
    return counter++;
  };
  console.log("Form Inside " + String(counter));
  return f;
}());

console.log(uniqueInteger());
console.log(uniqueInteger());
console.log(uniqueInteger());

The call of uniqueInteger should evaluate all body of that function event (let counter=0) why it's done one time and each calls?

VLAZ
  • 22,934
  • 9
  • 44
  • 60
malouke
  • 409
  • 2
  • 4
  • 6
  • 1
    `uniqueInteger` gets assigned the `f` function that's created by the wrapper function. It's a *closure* over the context where `counter` is defined. See [the linked question's answers](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) and my [old article *Closures are not complicated*](http://blog.niftysnippets.org/2008/02/closures-are-not-complicated.html). – T.J. Crowder Nov 22 '21 at 14:56

0 Answers0