Share via

Unable to Apply JavaScript Closures functionality

Ashok Kumar 60 Reputation points
2023-08-02T13:56:37.2666667+00:00

I'm trying to understand JavaScript Closures functionality in ASP.NET Core MVC project by following the first example in this article, but I'm keep on getting undefined as the result.

Below is how I've tried to write the code. I'm not sure how 18 can be substituted for val variable; but, Ideferred it for later analysis. Can smeone please suggest me how I can fix this issue!

function NinetimesFn() {
    var multFactor = 9;
    function InnerFunction(val) {
        multFactor = multFactor * val;
        return multFactor;
    }
    InnerFunction();
}

var result = NinetimesFn(18);
alert(result);


Developer technologies | ASP.NET Core | Other

Answer accepted by question author

Bruce (SqlWork.com) 84,086 Reputation points
2023-08-02T15:57:13.9033333+00:00

you pass a parameter to NinetimesFn(), but the function does not use it. also you do not return any valuetry:

function NinetimesFn(n) {
    var multFactor = 9;
    function InnerFunction(val) {
        multFactor = multFactor * val;
        return multFactor;
    }
    return InnerFunction(n); // call nested function with passed value (18)
}

var result = NinetimesFn(18);
alert(result);

you could also pass the 18 by closure which makes more sense:

function NinetimesFn(val) {
    var multFactor = 9;
    function InnerFunction() {
        // both values passed by closure 
        multFactor = multFactor * val;
        return multFactor;
    }
    return InnerFunction();
}

var result = NinetimesFn(18);
alert(result);

Was this answer helpful?

0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Ashok Kumar 60 Reputation points
    2023-08-02T16:04:43.2733333+00:00

    Thank you very much to all the industry experts from the bottom of my heart. I also got the solution/fix for the issue. Below is the modified code.

    function NinetimesFn() {
        var multiFactor = 9;
        return function (val) {
            multiFactor *= val;
            return multiFactor;
        }
    }
    
    var ninetimes = NinetimesFn(18);
    var result = ninetimes(18);
    alert(result);
    
    

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.