var createCounter = function(n) {
return function() {
let m = n;
n++
return m;
};
};
What happens here?
var createCounter = function(n) {
};
What was given by LeetCode was the outer declaration, the initialization of var createCounter, which was assigned a function that takes one argument, a number n.
π» Note: I personally never use var when declaring a variable, I always opt for let or const, but since this was the default, I'll keep it that way (there's nothing really wrong with using var).
Return a function
In the description it is said that we should return a function, which I did by writing
return function() {
};
Initial return and increment
The first return should be the number n itself. The next return should be one more then the number before and so on.
let m = n;
n++;
return m;
By declaring m and giving it the value of n, the first time we call the function the value of return m is what is was declared in the beginning, the value of n.
n++, which stand for increment the number n by 1, only happens after m is return. So, the second time we call the function, m will then be m + 1.
In general, I am bad at explaining technical stuff. So any advice is welcome to improve my explanation skills ππ½.