JavaScript 'bind': a less used magic

Apr 22, 2016
>>>

There is a method bind available in function.prototype of JavaScript. Do you know? May be.

I got to know about this in detail at quite a later time in my programming carrier. I heard and read about the method. But couldn’t find good example/use-case to use. Recently one of my colleagues came with a puzzle question, how to write this multiply function so that the following would return 120 the product of the numbers passed.

multiply(1)(2)(3)(4)(5);

He showed the solution as following:

function multiply (a) {
return function (b) {
return function (c) {
return function (d) {
return function (e) {
return a * b * c * d * e;
};
};
};
};
}

But, somehow I didn’t like the solution. As we can multiply that many numbers equal to the number of funcitons returned in chained fashion. And thought that partial function can be a resort to solve this problem. So my solution was:

'use strict';

// In non-strict mode we have to use this !== window (vide: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call)

var multiply = function (a, b) {
if (!b && (this !== undefined)) {
return a;
}
else {
return multiply.bind(null, !b? a: a * b);
}
};

But here we only have to call this as multiply(2)(3)(4)(5)(6)(7)(), with an extra parenthesis to call the last generated function. Also, we have to be careful about the sentinel constraint as described in the comment.

Until the last call of the method, it actually returns partial functions. And for the first and last case, we are relying on the fact, that this would be undefined in the first case and in the last call (the sentinel call), b would be undefined as well as this would be null not undefined.

It’s a good use-case to use bind. And with this implementation we are not restricting ourselves to the number of operands, can be passed.

Blog comments powered by Disqus