Introduction to Currying and Partial Application, some question

I figured out solution, no problems with that.

But when doing that, I accidentally wrote some nonsense like:

function add(x) {
  // Only change code below this line

  return x => y => z => x + y + z;

  // Only change code above this line
}

console.log(add(10)(20)(30));//[Function (anonymous)]

Can’t figure out what this code does and why)

Also in the description the bind was used. I can’t remember if it was present in the earlier curriculum.
I am running into snippets with bind when doing research on regular basis, but never used it yet. Is it time to do thorough research about this one? Just finished Functional Programming section.

You went one more level deeper into returning functions:

console.log(add(10)(20)(30)(40)); //90

The x that’s passed into add initially isn’t used, as the returned function also uses x as parameter name.

1 Like

bind is a method available to functions in JS.

It exists primarily to let you set the scope of methods taken from a given object; that’s a bit difficult to explain without exampls just using it, but it wraps the original function you’re binding in a new function with this set to whatever you want it to be (first argument passed to bind).

What it also lets you do is pass in arguments that get prefilled (second, third etc arguments passed to bind), allowing for partial application. Which is where it relates to functional programming – in this context, the primary purpose of bind isn’t important (I’m just passing null in as the first argument):

const add = (x, y) => x + y;

// Following creates a function that is like
//
//    const add2 = (x) => {
//      return add(2, x);
//    };
const add2 = add.bind(null, 2);

console.log(add(1, 2)) // 3
console.log(add2(1)) // 3

It’s occasionally useful

1 Like

Thanks! Not the easiest thing to wrap my mind around, I should say. I will play around it.