javascript interactive

JavaScript Interactive — a console crash course


3.8 Currying & Bound Methods

Warning: Your browser may be outdated or unsupported.

The JavaScript console is known to display some of the examples incorrectly in Internet Explorer 8 or older.
>>>
function mul(a, b) { return a * b; }

  
Let's first create a simple function to multiply two values.
>>>
var factorThree = mul.bind(null, 3);

  
Using the built-in bind() method for function objects, we can create a new function where one or more of the arguments are already set. This is also called "currying" and is another way to create higher-order functions.
>>>
factorThree(2)
6
When calling the new function, the original function is called with both the supplied argument and the bound one.
>>>
function factor(a) {
    return mul.bind(null, a);
}

  
With the help of bind(), it is now possible to re-implement the factor() function from the previous page.
>>>
[0, 1.5, -3].map(factor(3))
[0, 4.5, -9]
Using the built-in map() function for arrays also shortens the previous example code.
>>>
var arrMap = [].map.bind([0, 1.5, -3])

  
The first argument to the bind() method is the object that the function is bound to (as a method). So here we create a version of map() that applies any function to the same array object.
>>>
arrMap(factor(3))
[0, 4.5, -9]
This way of creating functions from object methods is actually very useful when mixing object-oriented programming and functional programming styles in JavaScript.
>>>

Index 1 2 3 4 5 6 7 8 9