Currying and Partially Applied Functions

A 'curry' function is one that returns a function that can be invoked at a later time. The returned function relies upon some information that was provided to the curry function. The returned function is often referred to as a 'partially applied' because it has some of the information it needs (provided by the curry function) but might still need more information (via parameters) when it is actually invoked. John Resig described it like this: Filling in the first couple arguments of a function (and returning a new function) is typically called currying.

 

This example demonstrates a curried function at it's most basic level:

function displayText(el){
return function(text){
el.innerHTML = text;
}
}
// returns a function that inserts text into a specific element,
// the element is provided by the curried function

 

Here's how you might use the partially applied function:

var displayInInfoDiv = displayText(document.getElementById("infoDiv"));

document.getElementById("helpBtn").oclick = function(){
displayInfoDiv("Help....");
};

document.getElementById("contactBtn").oclick = function(){
displayInfoDiv("Contact...");
};

 

Hopefully this demonstrates how you might use currying as a convenience, and to reduce duplicate code.