Hi, I’m trying to understand the concept of closure but something about using functions to return other functions trips me up, could someone read through my post and correct me If anything I say while trying to explain it to myself is wrong?
Normally when we declare a function we also declare the arguments it should receive. If we call a function with too many arguments additional ones will be ignored and if we provide too few they will be passed as undefined.
For example:
typefunction test(x) {
return x
}
console.log(test()) //undefined
console.log(test(420)) //420
This is expected behavior, when return statement is encountered first we evaluate whatever is to the right of it, then it returns it and e.g. assigns it to a variable.
But something strange happens when I try to make a function which returns a function.
let multiplyNumber = function (multiplier) {
return function(number){
return number*multiplier
}
}
twice=multiplyNumber(2)
console.log(twice(10)) //20
console.log(multiplyNumber(52)) //[Function]
Here lies the problem, when I’ve called:
twice=multiplyNumber(2)
multiplyNumber(2) it didn’t try to execute the inner function with missing “number” argument and return undefined.
Instead it treats the inner function purely as a function declaration and returned a function object (like with my second console.log statement with 52) and along with it passed a scope in which that function object was created, so the twice variable is being assigned to the anonymous function returned by multiplyNumber with variable called “multiplier” already preinitialized to be equal to 2.
It follows that when we then call twice(10) the 10 is passed as an argument to the anonymous function and multiplied by preinitialized multiplier thus returning the value 20.
What has been created here is essentially a function generator,
Did I get the concepts right or are there some flaws in my understanding?