Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do javascript variables in closure functions not reset to a default when called multiple times?

In the code below please can someone explain to me why multiple calls to counter result in the value of i increasing each time it is called?

My understanding is that as we specifically set i = 0; in makeCounter, each time makeCounter is called through the counter variable, i should be reset to 0. I cannot understand why this is not the case.

function makeCounter() {
  // `i` is only accessible inside `makeCounter`.
  var i = 0;

  return function() {
    console.log( ++i );
  };
}

// Note that `counter` and `counter2` each have their own scoped `i`.

var counter = makeCounter();
counter(); // logs: 1
counter(); // logs: 2
like image 264
BenM Avatar asked Dec 27 '22 01:12

BenM


1 Answers

each time makeCounter is called through the "counter" variable

That is wrong.

You're only calling makeCounter() once – at var counter = makeCounter();.
counter is a reference to the returned function, which closes over the i variable.

Calling counter() will execute this returned function, just like any other function.

The behavior you're expecting would happen if you write makeCounter()() multiple times.

like image 194
SLaks Avatar answered May 04 '23 10:05

SLaks