50 Mins advanced
21. Advanced Functions
Functional
Advanced Functions
Functional programming involves treating functions as pure data. You can pass them around, return them from other functions, and partially apply their arguments.
๐ Higher-Order Functions
A Higher-Order function is any function that takes another function as an argument, OR returns a function. You use these every day (e.g., map() and filter()).
// A Higher-Order Function
function repeatTask(times, taskFunc) {
for (let i = 0; i < times; i++) {
taskFunc(i);
}
}
// Passing an anonymous function as the task
repeatTask(3, (index) => {
console.log("Executing task round", index);
});
OutputExecuting task round 0
Executing task round 1
Executing task round 2
Executing task round 1
Executing task round 2
๐ Currying
Currying is the process of converting a function that takes multiple arguments into a sequence of functions that each take a single argument. It relies heavily on Closures.
// Standard function:
// const multiply = (a, b) => a * b;
// Curried function:
const curriedMultiply = (a) => {
return (b) => {
return a * b;
};
};
// Partial Application: Lock the first argument in memory
const double = curriedMultiply(2);
const triple = curriedMultiply(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15
Output10
15
15
Knowledge Check
Ready to test your understanding of 21. Advanced Functions?