JavaScript – How Function Returning a Function Works

higher-order-functionsjavascript

I'm having a hard time understanding exactly what is happening in the code here and how this script is changing other functions.

This is taken from eloquentjavascript.net chapter 5 on higher order functions.

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

Best Answer

Since it's not clear what part of this is confusing you, let's take this step by step.

1) Boolean is a function. In this case, it takes one argument, and returns either true or false depending on whether the argument was truthy or falsy. So if it helps, you could replace Boolean with function(x) { return !!x; } and get roughly the same behavior.

2) This line:

noisy(Boolean)(0);

is interchangeable with:

var func = noisy(Boolean);
func(0);

Assuming the identifier func is not used anywhere else in your code.

3) noisy(Boolean) obviously calls the noisy function, with f set to the function Boolean. The call to noisy then returns a function like this:

function(arg) {
    console.log("calling with", arg);
    var val = Boolean(arg);
    console.log("called with", arg, "- got", val);
    return val;
}

4) The function returned by noisy is then called with 0 as the value of arg. That effectively does the following:

console.log("calling with", 0);
var val = Boolean(0);
console.log("called with", 0, "- got", val);
return val;

5) If #1 made sense, then it shouldn't be surprising that Boolean(0) evaluates to false. From there it should be obvious why the output is what it is.

Related Topic