I am currently trying to understand closures but there is something which I don't seem to get no matter how many videos or forum posts I check.
As an example, here is a simple closure with a parentFunction
and a childFunction
:
function parentFunction(a, b) {
function childFunction() {
return a + b;
}
return childFunction;
}
What I don't understand is why is it necessary to assign the parentFunction
to a variable and call it if I want the value returned from the childFunction
:
let test = parentFunction(1, 2)
console.log(test())
;
If I called the parent function directly, shouldn't it have the same outcome? For example:
console.log(parentFunction(1, 2))
;
Isn't it the same as assigning it to the variable first but with an extra step? Is it just because of the syntax being that way and that's it?