skip to Main Content

I’m not able to figure out the reason for this behavior, can any one help me understand

  let counter= (function (){
    let count = 0;
    return function() {
        count+=1;
        return count;
    }
})()

for (let i = 0; i< 3; i++){
    console.log(counter());
}

This prints an output of

 1
 2
 3

Where as the below code

 function increment() {
    let count = 0;
    return function() {
        count+=1;
        return count;
    }
}

for (let i = 0; i< 3; i++){
    console.log(increment()());
}

Prints 1 1 1 1

2

Answers


  1. Chosen as BEST ANSWER

    Is it because let counter is pre-initialized with a function where count = 1 ; But in the other case, as the function is called every time, it's resetting the count to 0


  2. In the first example, the closure is created once and reused, so the state (count) is maintained across calls.

    In the second example, a new closure (and hence a new count variable) is created each time increment() is called, so the state is not shared across the loop iterations.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search