Anonymous Functions
Anonymous functions are exactly what they sound like: functions that have no name. They are incredibly useful when you need to define a function that will only be used once, usually to be passed immediately into a higher-order function.
Named vs Anonymous
Let’s say we have a function conversions that expects another function as its first argument:
function conversions(converter, x, y, z) {
const convertedX = converter(x);
const convertedY = converter(y);
const convertedZ = converter(z);
console.log(convertedX, convertedY, convertedZ);
}
We could define a helper function normally and pass it by name:
// Using a named function
function double(a) {
return a + a;
}
conversions(double, 1, 2, 3);
// Output: 2 4 6
However, if double is never going to be used anywhere else in the application, defining it separately wastes space. Instead, we can define it inline as an anonymous function:
// Using an anonymous function
conversions(
function (a) {
return a + a;
},
1, 2, 3
);
// Output: 2 4 6
Practical Example
When printing a batch of reports, you might need to apply a specific cost calculation to the data. Passing an anonymous function allows you to define that specific logic right where it’s used.
function printCostReport(costCalculator, message) {
const cost = costCalculator(message);
console.log(`Message: "${message}" Cost: ${cost} cents`);
}
// Passing an anonymous function that multiplies the length by 2
printCostReport(
function(msg) {
return msg.length * 2;
},
"Welcome!"
);