Glossary / First-class functions
First-class functions
JavaScript functions are first-class values: they can be assigned to variables, stored in objects and arrays, passed as arguments, returned from other functions, and created dynamically. This makes callbacks, event handlers, factories, middleware, and functional composition natural parts of the language. A function is also an object, but it has the additional capability of being called (and some functions can be constructed with new).
Function values and call behavior
function applyTwice(value, transform) {
return transform(transform(value));
}
const addOne = (x) => x + 1;
applyTwice(3, addOne); // 5
Passing a function does not invoke it: applyTwice(3, addOne) passes the function value, while addOne(3) calls it. The receiving API defines when and how often it invokes a callback, whether it awaits a returned Promise, what this is, and how callback exceptions propagate. Those are contract details, not guaranteed by “first-class.”
A method is a function stored in a property. Extracting it (const f = obj.method) does not preserve the original receiver for traditional functions; calling f() is different from obj.method(). Functions can have properties and prototypes, but arrows are not constructable and do not have an own this binding.
Design guidance
Use functions as values to separate policy from mechanism, but keep callback contracts explicit. Prefer named callbacks where they improve stack traces. Consider cancellation and cleanup for long-lived registrations. Avoid APIs that accept arbitrary callback behavior when a simple data parameter would be clearer.
Interview questions
- What does first-class mean? Functions can be treated as values and passed/stored/returned like other data.
- Does passing a function call it? No; the receiving code must invoke it.
- What should a callback contract define? Invocation timing/count, arguments, receiver, async behavior, error propagation, and cancellation/cleanup.
- Does extracting a method keep its
this? Not for an ordinary unbound method; the call expression supplies the receiver.