What Is Currying? – Definition, Meaning & Examples of Curried Functions
Currying means converting a function with multiple arguments to a series of functions with only one argument each.
Example of Currying in JavaScript
Consider the following code:
// Define an un-curried senseOrgans function:function senseOrgans(s1, s2, s3, s4, s5) { return `The 5 basic senses are the ${s1}, ${s2}, ${s3}, ${s4}, and ${s5}.`;}
// Invoke the senseOrgans() function:senseOrgans("eye", "nose", "ear", "mouth", "skin");
// The invocation above will return:// "The 5 basic senses are the eye, nose, ear, mouth, and skin."
The senseOrgans()
function above is an un-curried function with five (5) arguments. You can turn it into a curried function by converting it into a sequence of functions with only one argument each.
// Define a curried senseOrgans function:function senseOrgans(s1) { return function (s2) { return function (s3) { return function (s4) { return function (s5) { return `The 5 basic senses are the ${s1}, ${s2}, ${s3}, ${s4}, and ${s5}.`; }; }; }; };}
// Invoke the senseOrgans() function:senseOrgans("eye")("nose")("ear")("mouth")("skin");
// The invocation above will return:// "The 5 basic senses are the eye, nose, ear, mouth, and skin."
The senseOrgans()
function above is a curried function because we converted it from a function with multiple arguments to a series of functions with one argument each.
What Is the Advantage of Currying?
The primary advantage of a curried function is its flexibility. You can invoke a curried function without immediately supplying all its required arguments.
In other words, currying allows you to invoke a function in bits by storing each invocation’s returned function in a variable. Then, you can invoke the returned function whenever its argument is available.
Here’s an example:
// Invoke the senseOrgans() function:const noseOrgan = senseOrgans("nose");
// Invoke the noseOrgan's function:const eyeAndEarOrgans = noseOrgan("eye")("ear");
// Invoke the eyeAndEarOrgans' function:const skinOrgan = eyeAndEarOrgans("skin");
// Invoke the function in the skinOrgan variable:skinOrgan("mouth");
// The invocation above will return:// "The 5 basic senses are the nose, eye, ear, skin, and mouth."
Each variable in the example above contains a function initially returned from the senseOrgan()
function.
Defining senseOrgan()
as a curried function allowed us to invoke its returned functions at our own pace when we had the required arguments available.