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?
>Solution :
When you put it into a variable first, you’re also invoking it when logging the result.
let test = parentFunction(1, 2)
console.log(test());
// ^^
Substituting in parentFunction(1, 2) and removing the test variable entirely would be equivalent
console.log(test ()); // before
console.log(parentFunction(1, 2)()); // after
But your second version lacks the () at the end, which is why it’s not the same.
console.log(parentFunction(1, 2)()); // after
// ^^ your second version lacks this
parentFunction returns a function. You must call the function to get the resulting number from it, otherwise you have just the function.