Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Returning Value From JS Closures

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading