javascript currying parameters with .bind() method

I'm examining a code from Kyle's Simpson book "You Don't Know JS: this & Object Prototypes" and stuck on a code example, which is written below.

Could anybody explain in plain how bar variable after executing var bar = foo.bind(null, 2); piece of code saves "a" parameter as 2 and where it keeps that saved parameter, and why parameters is not overridden when bar(3); code executes?

function foo(a, b) {
  console.log(a, b);
  console.log("a:" + a + ", b:" + b);
}

foo.apply(null, [1, 10]);

var bar = foo.bind(null, 2);
bar(3);

1 answer

  • answered 2017-10-11 09:59 Rohit Agrawal

    You can also add extra parameters after the 1st (this) parameter and bind will pass in those values to the original function. Any additional parameters you later pass to the bound function will be passed in after the bound parameters.

    So in case of your example:

    function foo(a, b) {
      console.log(a, b);
      console.log("a:" + a + ", b:" + b);
    }
    
    var bar = foo.bind(null, 2);
    

    Here we have only passed one parameter after this reference parameter and that is for a. If you call it like this:

    bar();// here a is 2 and b is undefined(no parameter passed).
    
    bar(3);// a is 2 and b is 3
    

    bar(3); is equivalent to :

    foo.bind(null, 2, 3);
    bar();