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?
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
0to the console.It sounds like you wanted to declare
numberin a higher scope. For example:Then any calls to
num()(or the function it returns) will use the same globalnumbervariable.