mattnewbie mattnewbie - 5 months ago 13
Javascript Question

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);
return val;
};
}


noisy(Boolean)(0);

// calling with 0
// Called with 0 - got false


I understand that higher function can be functions that change other functions, like the example above. I understand why the second console.log gives
Called with 0 - got false
as it's output.


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

  2. Why does
    val
    have to be returned?


Answer

Let's break the code.

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

var fn = noisy(Boolean); // fn now is the inner function
var 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()`
    function noisy(f, arg) {
        return function () {
    
            // Arguments can still be accessed here
            console.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 used
    var 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.