skip to Main Content

I don’t understand why my returned function didn’t change the value of the variable from the outer function.

Hi, I wrote js function:

function num() {
    let number = 0;
    console.log(number)
    return function() {
        return number++
    }
}

then run it once. let add = num()
After that I run add() multiple times and it returned my number variable with new values, but when I decided to run num() function, in the console it would still return 0, as value of number. and I don’t understand why this happens, because isn’t returned function changing the value of number?

2

Answers


  1. when I decided to run num() function, in the console it would still return 0, as value of number

    Well, yes. Let’s take a look at the first two lines of code executed any time you invoke the num() function:

    let number = 0;
    console.log(number)
    

    There is no scenario in which those two lines of code would ever log anything but 0 to the console.

    It sounds like you wanted to declare number in a higher scope. For example:

    let number = 0;
    
    function num() {
      console.log(number);
    
      return function() {
        return number++;
      };
    }
    

    Then any calls to num() (or the function it returns) will use the same global number variable.

    Login or Signup to reply.
  2. The reason why the value of the number variable in the num() function does not change is because the number variable is a local variable to the num() function, and the returned function created by num() has access to this variable due to closure.

    When you call num(), a new number variable with an initial value of 0 is created. Then, the function returns another function that has access to the number variable through closure. This returned function increments the value of number every time it is called and returns the new value.

    So when you assign the returned function to the add variable and call it multiple times, the value of the number variable within the closure is incremented and returned each time. However, when you call num() again, a new number variable with an initial value of 0 is created again, and the old value of number is not affected.

    If you want to change the value of number in the num() function, you can modify the code by setting number variable at global scope or outside of the num() function.

    let number = 0;
    function num() {
      console.log(number)
      return function() {
          return number++
      }
    }
    
    let add = num() // 0 
    add()
    add()
    add()
    
    num() // 3
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search