j7an
j7an

Reputation: 114

Eloquent Javascript: Higher Order Functions

I'm going through Eloquent Javascript: Higher Order Functions example below and already read questions and answers here and here. But I'm still very confused.

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
  1. How can (0) be passed into noisy(f) since noisy() only takes one parameter and that is (Boolean)? I can see the inner function f(arg) is basically Boolean(0), but I don't understand how two parameters can get passed into a function that only allow one parameter. Would "noisy(Boolean)(0)(1)(2)(3);" be a valid function call? If so, how would you differentiate each value after Boolean within the noisy function? Which value will be referenced by "arg"?

  2. The book noted the example function is modifying another function. Which function is being modified? I'm not understanding what the author meant by "modified".

Upvotes: 0

Views: 467

Answers (2)

guest271314
guest271314

Reputation: 1

but I don't understand how two parameters can get passed into a function that only allow one parameter

noisy returns a function, Boolean is passed to noisy, 0 is passed to anonymous function returned from noisy, where f is Boolean, val becomes Boolean(0).

For example

function fn1(arg1) {
  return function fn2(arg2) {
    console.log(arg1, arg2)
  }
}

// Call fn1, inside fn1 fn2 is called with `"b"` as parameter.
fn1("a")("b") // `a b`, `fn2` 

Upvotes: 1

Aditya Singh
Aditya Singh

Reputation: 16660

This is the concept of currying in JavaScript where you can curry functions to return partially applied functions or pass in other functions

How can (0) be passed into noisy(f) since noisy() only takes one parameter and that is (Boolean)?

The answer to this is the curried function noisy() which expects a function f as parameter and returns another function. The returned function has a closure over noisy and as a result it can identify that Boolean was passed as parameter to noisy even after it was returned. That's why calling noisy(Boolean)(0) basically substitutes f=Boolean, arg=0

Refer this for more on currying: http://javascript.crockford.com/www_svendtofte_com/code/curried_javascript/ and closures: https://developer.mozilla.org/en/docs/Web/JavaScript/Closures

Upvotes: 0

Related Questions