Closure practice

I was practicing js closures for my understanding, Can any one help me in resolving the error “result is not a function”.
It would be of great help.
Below is the link:

Hi @vaishnavi_A.N

Your function xy() doesn’t have a return value. You see that in your last console log where it states “undefined”. So you’re trying to call “undefined” like a function.


Hello @mikoMK, I have corrected the code and thank you, but I have a question, despite writing the return statement, console.log(result) gives me undefined, why is it so?
Generally while storing the highest parent(outer most function) to a const “name”, and rendering that “name()”,why we are getting undefined?

To create closures you need to return the inner functions. They will then keep the scope they had when declared:

var x = 2;
function xy(){
    const a = 2;
    console.log(x +=2);

    childFunction = function(){
        const s = 10;
            const i = s*a;
            console.log('grandchild', i);
        return grandChildFunction;
    return childFunction;

const result = xy();
console.log("res", result)
result(); /* childFunction() */
result()(); /* grandChildFunction() */

Ohh I didn’t know that.
I mean to access innermost function,we need to use ()()
Again as usual you are Amazing man @mikoMK​:+1::+1:

I’m glad it was helpful. :slightly_smiling_face:
If you haven’t already I recommend reading the MDN article about closures:

1 Like

:+1: :+1:
Thank you @mikoMK.
I haven’t gone through this previously, going through now.

1 Like