This page looks best with JavaScript enabled

Curry Using Bind in Javascript

 ·   ·  ☕ 1 min read

You can use bind to bind variables of a function, and execute the said function later to get the desired result.

You have seen how how closures can be used in Javascript and a bit about currying functions. Here’s one more way of doing that.

We can bind available variables for a function and execute function at a later time.

Consider the below closure -

1
2
3
4
5
6
7
8
9
function getProduct(x) {
  return function(y) {
    return y * x;
  };
}

const twice = getProduct(2);

console.log(twice(3)); // 6

We may not want to create another variable doing the same thing for us - do we? Instead we bind one of the values, and do the final execution when the next variable is available.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function getProduct(x, y) {
  console.log("multiThis", x, y, x * y);
  // multiThis 2 3 6
  return x * y;
}

let twice = getProduct.bind(null, 2);
// Only initiation at this time with one variable.

console.log(twice(3)); // 6
// execute and print result

Using bind we can now fix variables incrementally and do the final function execution at a later time.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things