Functions as Values in JavaScript: First-Class Functions, Callbacks, Function Properties and Namespaces
JavaScript functions are first-class values: store them in variables, objects and arrays, pass them as callbacks, return them from other functions. Dispatch tables instead of switch, function properties for state and caching, and using functions (IIFEs) as private namespaces, compared with modules.
kvi5hnuCode Sprout team member6 min readOn this page
In many languages, functions are fixed parts of the program's structure. In JavaScript they're values, as ordinary as numbers and strings: you can assign them to variables, put them in arrays and objects, pass them to other functions and return them. This is called having first-class functions, and it's the foundation of callbacks, event handling, array methods, promises, React components and functional programming.
A function is an object you can refer to
When you write function cube(n) { return n ** 3; }, JavaScript creates a function object and stores a reference to it in the variable cube. The name is just a variable; other variables, properties and array elements can refer to the same function:

function cube(n) {
return n ** 3;
}
const alias = cube; // no parentheses: the function itself
const tools = { cube }; // a method
const steps = [cube, (n) => n + 1]; // array elements
console.log(alias(2), tools.cube(3), steps[0](4), steps[1](4));
console.log(alias === cube, alias.name);
8 27 64 5
true cube
The difference between cube and cube() matters: cube is the function; cube() calls it and gives you its result. Writing button.onclick = handleClick() instead of handleClick is a classic bug: it calls the function immediately and assigns its return value.
Passing functions: callbacks
A function passed to another function is called a callback: the receiving function "calls it back" when appropriate. You've used many already: map, filter, sort comparators, setTimeout, event listeners.
function repeat(times, action) {
for (let i = 1; i <= times; i++) action(i);
}
repeat(3, (n) => console.log(`round ${n}`));
const applyTwice = (fn, value) => fn(fn(value));
console.log(applyTwice((s) => s + "!", "hey"));
round 1
round 2
round 3
hey!!
Callbacks separate what to do from when or how often to do it. repeat handles the looping, the caller decides the action. sort handles the sorting algorithm, the caller decides the order. That's why one sort method can sort numbers, names and dates.
Returning functions
A function can create and return another function. The returned function remembers the variables of the function that made it (a closure, next article):
function makeMultiplier(factor) {
return (n) => n * factor;
}
const double = makeMultiplier(2);
const triple = makeMultiplier(3);
console.log(double(10), triple(10), makeMultiplier(5)(4));
20 30 20
Functions that take functions as arguments or return them are higher-order functions. They're covered in depth in article 69.
Dispatch tables: functions in objects
Storing functions in an object as a lookup table often replaces a long switch or if/else chain:
const operations = {
"+": (a, b) => a + b,
"-": (a, b) => a - b,
"*": (a, b) => a * b,
"/": (a, b) => a / b,
"**": Math.pow, // built-in functions work too
};
function calculate(a, operator, b) {
const operation = Object.hasOwn(operations, operator) ? operations[operator] : undefined;
if (typeof operation !== "function") {
throw new Error(`Unknown operator: ${operator}`);
}
return operation(a, b);
}
console.log(calculate(6, "*", 7), calculate(2, "**", 10));
try {
calculate(1, "%", 2);
} catch (err) {
console.log(err.message);
}
42 1024
Unknown operator: %
Adding an operator means adding one line, not editing control flow. The Object.hasOwn check prevents inherited names like "toString" from being treated as operators when the key comes from user input (article 48). Command handlers, keyboard shortcuts, message routers and reducers in state libraries all use this pattern.
For optional handlers, optional chaining calls a function only if it exists:
const hooks = { onSave: (doc) => `saved ${doc}` };
console.log(hooks.onSave?.("report"), hooks.onClose?.("report"));
saved report undefined
Functions have properties
Functions are objects, so they have properties. Built-in ones include name and length (articles 63 and 65), and you can add your own. A property on the function can hold state that persists between calls without a global variable:
function nextTicket() {
return nextTicket.counter++;
}
nextTicket.counter = 100;
console.log(nextTicket(), nextTicket(), nextTicket.counter);
100 101 102
The same idea works for caching (memoization): store computed results on the function so repeated calls are instant.
function fibonacci(n) {
if (n in fibonacci.cache) return fibonacci.cache[n];
return (fibonacci.cache[n] = fibonacci(n - 1) + fibonacci(n - 2));
}
fibonacci.cache = { 0: 0, 1: 1 };
console.log(fibonacci(50), Object.keys(fibonacci.cache).length);
12586269025 51
Without the cache, fibonacci(50) would make billions of calls; with it, each value is computed once.
The drawback: function properties are public. Any code can do nextTicket.counter = "broken" and break the function. Closures (next article) keep such state truly private, which is why they're usually preferred. Function properties are still used for metadata, such as Component.displayName in React or attaching configuration to a handler.
Functions as namespaces
Variables declared inside a function aren't visible outside it. Before ES2015, var was function-scoped and there were no modules, so the only way to keep a script's helper variables from colliding with other scripts on the same page was to wrap the code in a function and call it immediately: an IIFE (immediately invoked function expression, article 63):
const counterModule = (function () {
let count = 0; // private: nothing outside can reach it
function increment() {
return ++count;
}
return { // the public API
increment,
get value() { return count; },
};
})();
counterModule.increment();
counterModule.increment();
console.log(counterModule.value, counterModule.count);
2 undefined
This is the module pattern, which powered libraries like jQuery for years. The leading parenthesis turns function into an expression, since a statement can't start with an anonymous function. You may also see !function () {...}() or void function () {...}() in minified code, which do the same thing.
Today: modules and blocks
Modern JavaScript provides better tools for the same goal:
| Goal | Old way | Modern way |
|---|---|---|
| Keep a file's variables private | IIFE around the file | ES modules: every module has its own scope (part 10) |
| Keep temporary variables private | IIFE | a block { ... } with let/const |
| Hide state behind an API | module pattern | module exports, or a class with #private fields (part 9) |
{
const temporary = "only in this block";
}
console.log(typeof temporary);
undefined
IIFEs remain useful for running async code at the top level of a script, (async () => { ... })(), where top-level await isn't available, and for computing a const value with several statements. You'll also meet them constantly when reading older code and bundler output.
Common questions
What does "first-class functions" mean?
That functions are values like any other: they can be stored in variables and data structures, passed as arguments, returned from functions, and created at runtime. Languages without this need workarounds such as interfaces with one method.
Why does my event handler run immediately?
You probably wrote addEventListener("click", handle()), which calls handle right away and registers its return value. Pass the function itself (handle), or an arrow that calls it (() => handle(id)).
Can two functions be compared?
Only by identity: f === g is true only if both refer to the same function object. Two functions with identical code are different objects. That's why removing an event listener requires the same function reference that was added.
Is a dispatch table faster than switch?
Speed is rarely the reason to choose; both are fast. Tables win on extensibility (handlers can be added or registered at runtime) and readability when there are many cases.
Summary
- Functions are first-class values: assign them, store them in objects and arrays, pass them and return them.
fnis the function;fn()is its result. - A callback is a function passed to another function to be called later; it separates what to do from when to do it.
- Functions that take or return functions are higher-order functions.
- Dispatch tables (objects of functions) replace long
switchstatements; check keys withObject.hasOwnwhen they come from input. - Functions can carry their own properties for state, caches and metadata, though those are public.
- An IIFE creates a private scope; modules and block scope now cover most of its old uses.
Practice Questions
What does this print?
const fns = [Math.max, Math.min];
console.log(fns.map((f) => f(3, 9, 5)));
Answer
[ 9, 3 ]. Each element is a function, called with the same arguments.
What's wrong with setTimeout(showMessage("Saved"), 1000), and how do you fix it?
Answer
It calls showMessage immediately and passes its return value (probably undefined) to setTimeout. Pass a function: setTimeout(() => showMessage("Saved"), 1000).
Rewrite this with a dispatch table:
if (kind === "circle") return Math.PI * r ** 2;
else if (kind === "square") return r * r;
Answer
const area = { circle: (r) => Math.PI * r ** 2, square: (r) => r * r };
And then return area[kind](r);, ideally checking Object.hasOwn(area, kind) first.
What does this print?
const counter = (() => { let n = 0; return () => ++n; })();
counter();
console.log(counter(), typeof n);
Answer
2 undefined. The IIFE returns an arrow function that keeps updating its private n; outside, n doesn't exist.
Previous: JavaScript Function Parameters: Defaults, Rest Parameters, arguments, Spread and Destructuring
Next: JavaScript Closures Explained: Lexical Scope, Private State, Loops and Memory

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.