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
Well, yes. Let’s take a look at the first two lines of code executed any time you invoke the
num()
function: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:Then any calls to
num()
(or the function it returns) will use the same globalnumber
variable.The reason why the value of the number variable in the
num()
function does not change is because the number variable is alocal variable
to thenum()
function, and the returned function created bynum()
has access to this variable due to closure.When you call
num()
, anew number
variable with an initial value of0
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 newnumber
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 atglobal scope
or outside of thenum()
function.