Console Learner — An interactive JavaScript course.


3.8 Currying & Bound Methods

>>>
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 is bound to a particular array.
>>>
arrMap(factor(3))
[0, 4.5, -9]
This way of creating functions bound to an object is actually very useful when mixing object-oriented programming and functional programming styles in JavaScript.
>>>

The console allows you to interact with the course material and examples. Use the following keys:

A special logging function is also available:


Need more magic? Check out the other developer tools on this site.