Skip to content Skip to sidebar Skip to footer

Why Does This Function Have A Second Parameter In Separate Brackets?

function noisy(f) { return function (arg) { console.log('Calling with', arg); var val = f(arg); console.log('Called with', arg, '- got', val); r

Solution 1:

Let's break the code.

functionnoisy(f) {
    returnfunction (arg) {
        console.log("Calling with", arg);
        var val = f(arg);
        console.log("Called with", arg, "- got", val);
        return val;
    };
}

varfn = noisy(Boolean); // fn now is the inner functionvar value = fn(0);       // Calling the inner function

As seen in the code, noisy is a function which returns another function when invoked which accepts a single parameter.

So, in the below statement

noisy(Boolean)(0);

Boolean is passed as parameter to the noisy function and 0 is passed to the inner function.

  1. I don't understand why the second parameter (0) is contained in a second pair of brackets, & not with Boolean?

    you can, but for that some things need to be changed. This uses the concept of closure where the inner function has the access to the parameters of the outer function.

    // Pass two arguments to `noisy()`functionnoisy(f, arg) {
        returnfunction () {
    
            // Arguments can still be accessed hereconsole.log("Calling with", arg);
            var val = f(arg);
            console.log("Called with", arg, "- got", val);
            return val;
        };
    }
    
    // To call, the second braces need to be usedvar val = noisy(Boolean, 0)();
    
  2. Why does val have to be returned?

    That's totally upto you. If you want to get some value from the function, you can return the value and catch/assign it in other variable.

Post a Comment for "Why Does This Function Have A Second Parameter In Separate Brackets?"