JavaScript and TypeScript course ยท Module 12: Functional Programming
Currying and Partial Application
In this lesson5
Imagine the dinosaur feeding system in the park. Each species has its own requirements - type of food, portion size, and feeding time. Instead of providing all parameters every time, we can prepare "pre-configured" functions for a given species. This is exactly what currying does - it transforms a multi-argument function into a sequence of single-argument functions.
There is also a second, more technical problem. pipe from the previous lesson passes exactly one value to each stage, so a function that needs a species, a food and a portion simply does not fit into it. We need a way to set some of the arguments in advance and end up with a single-argument function.
What is Currying?
Currying is a technique of transforming a function that takes multiple arguments into a sequence of functions, each taking exactly one argument.
Let's start with a regular function with three parameters and its curried version written the classic way, with nested function expressions:
// Regular function with 3 arguments
function feedDinosaur(species, food, portion) {
return species + ' gets ' + portion + 'kg of ' + food;
}
feedDinosaur('T-Rex', 'meat', 50);
// Curried version - sequence of single-argument functions
function feedDinosaurCurried(species) {
return function(food) {
return function(portion) {
return species + ' gets ' + portion + 'kg of ' + food;
};
};
}
feedDinosaurCurried('T-Rex')('meat')(50);Both calls return 'T-Rex gets 50kg of meat'. The call feedDinosaurCurried('T-Rex') does not feed anyone yet, it only returns a function waiting for the food, and only the third pair of parentheses runs the actual logic. The inner functions remember species and food thanks to closures, which we will look at in the next lesson.
Arrow functions let you write the same thing much more briefly, because each arrow is another stage:
// Same thing with arrow functions (more concise)
const feedCurried = (species) => (food) => (portion) =>
species + ' gets ' + portion + 'kg of ' + food;Read it from the left: the function of the species returns a function of the food, which in turn returns a function of the portion. Only the notation has changed, the behavior is identical to the version with function.
Practical Use of Currying
The real power of currying lies in creating specialized functions. This time the last stage returns a feeding object with a timestamp:
const feedCurried = (species) => (food) => (portion) =>
({ species, food, portion, timestamp: Date.now() });
// Specialized functions for species
const feedRex = feedCurried('T-Rex');
const feedRexMeat = feedRex('meat');
// Using specialized functions
feedRexMeat(50); // { species: 'T-Rex', food: 'meat', portion: 50, ... }
feedRexMeat(30); // { species: 'T-Rex', food: 'meat', portion: 30, ... }
// Can also be used for another species
const feedBrachio = feedCurried('Brachiosaurus');
const feedBrachioPlants = feedBrachio('plants');
feedBrachioPlants(200); // { species: 'Brachiosaurus', food: 'plants', portion: 200, ... }feedRex and feedRexMeat are ordinary functions that you can store, pass around and call many times, while feedCurried stays general and handles the Brachiosaurus without any trouble. The notation { species, food, portion } is shorthand for { species: species, ... }. A technical note: Date.now() makes the last stage impure, because two calls with the same portion give different timestamps. The version without the time, const feed = (species) => (food) => (portion) => ({ species, food, portion }), is pure.
Universal Curry Function
We can write a universal curry function that automatically transforms any function. The key is the fn.length property, which is the number of parameters the function declares (excluding the rest parameter and any parameters from the first one with a default value onwards):
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn(...args);
}
return (...moreArgs) => curried(...args, ...moreArgs);
};
}curried collects arguments. Once it has at least as many as fn.length, it calls the original, and otherwise it returns a function that will add more. Let's check it on a function that builds an enclosure:
// Usage
function createEnclosure(zone, type, capacity, voltage) {
return { zone, type, capacity, voltage };
}
const curriedCreate = curry(createEnclosure);
// Can be called in various ways:
curriedCreate('A')('carnivore')(5)(10000);
curriedCreate('A', 'carnivore')(5, 10000);
curriedCreate('A', 'carnivore', 5)(10000);
curriedCreate('A', 'carnivore', 5, 10000);
// All calls produce the same resultEvery call returns { zone: 'A', type: 'carnivore', capacity: 5, voltage: 10000 }. Strictly speaking, a version that accepts several arguments at once combines currying with partial application. That is also how the curry functions in the Ramda and lodash libraries work. A trap: a function declared as (...args) => ... has a length of 0, so curry will call it immediately.
Partial Application
Partial application is a related technique - it "freezes" some of a function's arguments, creating a new function with fewer parameters.
partial takes a function and any number of starting arguments (presetArgs), and returns a function waiting for the rest (laterArgs). The spread operator glues both lists into a single call:
function partial(fn, ...presetArgs) {
return (...laterArgs) => fn(...presetArgs, ...laterArgs);
}Let's apply it to the incident logging function used by the whole park security team, and build a few specialized loggers out of it:
// Incident logging function
function logIncident(severity, zone, message) {
return '[' + severity + '] Zone ' + zone + ': ' + message;
}
// Specialized loggers
const logCritical = partial(logIncident, 'CRITICAL');
const logWarning = partial(logIncident, 'WARNING');
const logCriticalZoneA = partial(logIncident, 'CRITICAL', 'A');
logCritical('B', 'Fence breach detected');
// '[CRITICAL] Zone B: Fence breach detected'
logCriticalZoneA('T-Rex escaped!');
// '[CRITICAL] Zone A: T-Rex escaped!'In logCritical one argument is frozen, and in logCriticalZoneA two at once. The original logIncident has not changed and still takes three arguments. The built-in bind gives the same effect: logIncident.bind(null, 'CRITICAL').
Currying vs Partial Application
Although both techniques create specialized functions, they differ in how they work:
- Currying: always creates a chain of single-argument functions
- Partial application: "freezes" any number of arguments at once
Specializing through currying always has the same stages: you define a general curried function, you pass the first argument and get a partially applied function, further arguments narrow it down, and the last one returns the result. My advice: write functions for pipelines in the order "configuration first, data last", for example filterBy(key)(value)(arr). Once the configuration is given, what remains is a single-argument function ready for pipe, and for a one-off freezing of a few arguments of an existing function, partial is enough. In the final project you will build the tools for filtering readings exactly this way.
Remember: currying is a feeding station configured step by step - species, food, portion - and every setting gives you a new machine that is ready to work.
Code for this lesson: index.js
// Currying and partial application
console.log("=== Jurassic Park - Staged Species Processing ===\n");
// --- EXAMPLE 1: Basic currying ---
console.log("--- Currying: Feeding system ---");
const feedDinosaur = (species) => (food) => (portion) =>
`${species} gets ${portion}kg of ${food}`;
// Specialized functions
const feedRex = feedDinosaur("T-Rex");
const feedRexMeat = feedRex("meat");
console.log(feedRexMeat(50)); // T-Rex gets 50kg of meat
console.log(feedRexMeat(30)); // T-Rex gets 30kg of meat
const feedBrachio = feedDinosaur("Brachiosaurus");
console.log(feedBrachio("plants")(200)); // Brachiosaurus gets 200kg of plants
// --- EXAMPLE 2: A universal curry function ---
console.log("\n--- Universal curry ---");
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn(...args);
}
return (...moreArgs) => curried(...args, ...moreArgs);
};
}
function createEnclosure(zone, type, capacity, voltage) {
return { zone, type, capacity, voltage };
}
const curriedCreate = curry(createEnclosure);
// Different ways of calling it
const r1 = curriedCreate("A")("carnivore")(5)(10000);
const r2 = curriedCreate("A", "carnivore")(5, 10000);
const r3 = curriedCreate("A", "carnivore", 5, 10000);
console.log("Call 1:", JSON.stringify(r1));
console.log("Call 2:", JSON.stringify(r2));
console.log("Identical?", JSON.stringify(r1) === JSON.stringify(r2));
// Specialized factories
const createCarnivoreZone = curriedCreate("X")("carnivore");
console.log("Zone X-5:", JSON.stringify(createCarnivoreZone(5)(15000)));
console.log("Zone X-10:", JSON.stringify(createCarnivoreZone(10)(20000)));
// --- EXAMPLE 3: Partial application ---
console.log("\n--- Partial application ---");
function partial(fn, ...presetArgs) {
return (...laterArgs) => fn(...presetArgs, ...laterArgs);
}
function logIncident(severity, zone, message) {
return `[${severity}] Zone ${zone}: ${message}`;
}
const logCritical = partial(logIncident, "CRITICAL");
const logWarning = partial(logIncident, "WARNING");
const logCriticalA = partial(logIncident, "CRITICAL", "A");
console.log(logCritical("B", "Fence breach"));
console.log(logWarning("A", "Sensor malfunction"));
console.log(logCriticalA("T-Rex escaped!"));
// --- EXAMPLE 4: Currying with map/filter ---
console.log("\n--- Currying in practice ---");
const filterByField = curry((field, value, arr) =>
arr.filter((item) => item[field] === value)
);
const dinosaurs = [
{ name: "Rex", diet: "carnivore", zone: "A" },
{ name: "Blue", diet: "carnivore", zone: "A" },
{ name: "Brachio", diet: "herbivore", zone: "B" },
{ name: "Stego", diet: "herbivore", zone: "B" },
];
const filterByDiet = filterByField("diet");
const getCarnivores = filterByDiet("carnivore");
const getHerbivores = filterByDiet("herbivore");
console.log("Predators:", getCarnivores(dinosaurs).map((d) => d.name));
console.log("Herbivores:", getHerbivores(dinosaurs).map((d) => d.name));Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is currying in functional programming?
2. How does partial application differ from currying?
Hands-on tasks in the game
- Code editor
Use a universal curry function to create specialized filters and loggers.
- Vertical ordering
Arrange the stages of creating a specialized function through currying:
- Click in order
Arrange the elements of a curried arrow function:
- Code editor
Use partial() to create specialized filters and combine them into a pipeline with pipe().