Functions are first-class values
Here JavaScript hands you a power that surprises people coming from other languages: functions are values like any other. You can store them in variables, put them in arrays, pass them as an argument and return them from another function, just like you would with a number or a string. This is called "first-class functions".
Passing a function as an argument
A function that receives another function is called a higher-order function:
function apply(value, operation) {
return operation(value);
}
const double = n => n * 2;
console.log(apply(5, double)); // 10
Returning a function
function multiplier(factor) {
return n => n * factor;
}
const byThree = multiplier(3);
console.log(byThree(10)); // 30
This deceptively simple idea is the foundation of JavaScript's most powerful patterns. When a function "remembers" values from where it was born, you have a closure: you'll unlock it in the next module, and that's where functions go from handy tool to genuine superpower.
Examples
Store functions in an object and call them
const operations = {
add: (a, b) => a + b,
subtract: (a, b) => a - b,
};
console.log(operations.add(2, 3)); // 5
console.log(operations.subtract(7, 4)); // 3