1

In Chapter 5 of the book Eloquent JavaScript, there's this example that I don't quite understand. It's the noisy function:

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

When noisy is called, it has two arguments (Boolean)(0). How does that work? Can you call functions and place arguments in that manner? Any help is greatly appreciated, thanks!

Brian
  • 189
  • 3
  • 13
  • 3
    It's calling 2 functions, noisy, then the anonymous function returned by noisy. – Alexander O'Mara Jan 01 '16 at 01:19
  • *"When noisy is called, it has two arguments"* No, it only has one argument. the `(0)` is a separate call of a different function. –  Jan 01 '16 at 01:32

2 Answers2

2

Can you call functions and place arguments in that manner?

Yes, where a function is returned from initial function

function noisy(f) {
  // return anonymous function 
  // `f` : `Boolean` , `arg` : `0`
  return function(arg) {
    // `arg` : `0`
    console.log("calling with", arg);
    // `f` : `Boolean` , `arg` : `0`
    var val = f(arg);
    // `arg` : `0` , `val` : `false`
    console.log("called with", arg, "- got", val);
    // return `false` : `Boolean(0)`
    return val;
  };
}
// call `noisy` with `Boolean` as parameter,
// where anonymous function returned from `noisy`
// call anonymous function returned from `noisy` with `0`
// as parameter
noisy(Boolean)(0);
guest271314
  • 1
  • 15
  • 104
  • 177
1

Boolean is being passed into noisy as the parameter f. noisy itself returns a function and 0 is being passed into that returned function as the parameter arg.

enkrates
  • 626
  • 1
  • 6
  • 17