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 -
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.
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.