In JavaScript, a function is a value, just like a number or a string. That is what “first-class” means: functions can be used anywhere a value can.
1. Stored in variables, arrays and objects
const double = n => n * 2;
const operations = [double, n => n + 1, Math.sqrt];
console.log(operations.map(fn => fn(16))); // → [32, 17, 4]
const calculator = {
add: (a, b) => a + b,
multiply: (a, b) => a * b
};
console.log(calculator.multiply(3, 4)); // → 12
2. Passed as arguments
function applyTo(numbers, transform) {
return numbers.map(transform);
}
console.log(applyTo([1, 2, 3], n => n * 10)); // → [10, 20, 30]
3. Returned from functions
function makeAdder(amount) {
return function (n) { return n + amount; };
}
const addFive = makeAdder(5);
console.log(addFive(10)); // → 15
What this makes possible
A lot of everyday JavaScript depends on it:
- Callbacks and event handlers: you hand a function to the browser.
- Array methods:
map,filterandsortreceive your rules as functions. - Closures: returned functions remember where they came from (Closures).
- Higher-order functions: functions that work with functions (Higher-Order Functions).
- Strategies: choose behaviour by picking a function.
const formatters = {
currency: n => "$" + n.toFixed(2),
percent: n => (n * 100).toFixed(0) + "%",
plain: n => String(n)
};
function show(value, style) {
return (formatters[style] ?? formatters.plain)(value);
}
console.log(show(5, "currency")); // → $5.00
console.log(show(0.25, "percent")); // → 25%
console.log(show(7, "unknown")); // → 7
Instead of a long switch statement, the code picks a function from an object.
Functions have properties too
Functions are objects, so they have a name and a length (their number of parameters), and you can attach your own properties.
function greet(a, b) {}
console.log(greet.name, greet.length); // → greet 2
Comparing functions
Two functions with the same code are still different values:
console.log((() => 1) === (() => 1)); // → false
Pass the function, do not call it
A very common bug is calling a function where you meant to pass it, as in setTimeout(run(), 100). See Functions.