Functions as values: store, pass, return
A function in JavaScript is a value of type object with the one extra ability that it can be called. Everything else that holds for a number holds for it: it can be stored in a binding, put in an array or in a property of an object, passed as an argument and returned from another call. Calling it is one operation among several, written with parentheses after the value.
That single fact is what makes the rest of this part possible. A function that accepts another function is a higher-order function, and map, filter, setTimeout and every event handler in the browser are built the same way. This lesson shows the four moves on their own, and the next lessons put them to work.
A function is a value
A declaration and an arrow both create a function and bind it to a name, and the name can be used without parentheses to mean the function itself. An array of functions and an object whose values are functions are ordinary data structures, and a property holds a function just as it holds a string.
function double(value) {
return value * 2;
}
const triple = (value) => value * 3;
const operations = [double, triple, (value) => value + 1];
console.log(operations[0](5), operations[1](5), operations[2](5));
const table = { double, triple };
console.log(table.double(5), table.triple(5));
console.log('typeof:', typeof double);
console.log('name:', double.name);
console.log('declared parameters:', double.length);
node store.js
10 15 6
10 15
typeof: function
name: double
declared parameters: 1
The call of an element of an array needs two pairs of parentheses: operations[0] is the function and (5) calls it. The object literal { double, triple } is shorthand for { double: double, triple: triple }, so the keys carry the names the functions already had. name and length are properties of the value, not of the binding, and a function keeps them wherever it is put.
Passing a function to a function
A parameter accepts a function as readily as it accepts a number, and the body calls it when the work needs doing. The caller decides which function, and the callee decides when and with what arguments it runs. That division is the whole idea of a callback, and it is also how sort learns how to compare two items.
function double(value) {
return value * 2;
}
function applyTwice(fn, value) {
return fn(fn(value));
}
console.log('twice double:', applyTwice(double, 3));
console.log('twice add ten:', applyTwice((value) => value + 10, 3));
const words = ['pear', 'fig', 'banana'];
const byLength = (a, b) => a.length - b.length;
console.log('sorted:', [...words].sort(byLength).join(','));
console.log('mapped:', words.map((word) => word.length).join(','));
node pass.js
twice double: 12
twice add ten: 23
sorted: fig,pear,banana
mapped: 4,3,6
applyTwice knows nothing about doubling or adding: it takes a function and a value and calls the function twice. The comparator of sort is the same bargain in the other direction, because the array does the moving and the caller only says which of two items comes first. The spread in [...words] keeps the original order intact, since sort changes the array it is called on.
Returning a function
A function may also hand a function back. The returned function keeps the parameters of the call that created it, which is the closure of the lesson on closures, and the caller gets a specialised function built from a general one.
function multiplier(factor) {
return (value) => value * factor;
}
const double = multiplier(2);
const triple = multiplier(3);
console.log(double(7), triple(7));
console.log('a returned function is:', typeof double, 'with', double.length, 'parameter');
function makeLogger(prefix) {
return (message) => `[${prefix}] ${message}`;
}
const warn = makeLogger('warn');
console.log(warn('disk almost full'));
node return.js
14 21
a returned function is: function with 1 parameter
[warn] disk almost full
Two calls of multiplier produced two functions that behave differently, and neither one needs the other: each closed over its own factor. The logger is the same pattern with a string, and it is how a library offers createLogger('warn') without a global setting. Nothing here is special syntax: a function is a value, so a call may produce one.
A table of functions
An object of functions turns a chain of branches into data. The caller names a command, the object looks it up, and the function that was found runs. Adding a command means adding a key, and the lookup can be guarded so that a name the table does not know is an error rather than a crash.
const commands = {
add: (a, b) => a + b,
sub: (a, b) => a - b,
};
function run(command, a, b) {
const handler = commands[command];
if (!Object.hasOwn(commands, command)) {
throw new RangeError(`unknown command: ${command}`);
}
return handler(a, b);
}
console.log(run('add', 7, 2));
console.log(run('sub', 7, 2));
try {
run('toString', 1, 2);
} catch (error) {
console.log(error.name + ': ' + error.message);
}
console.log('names in the table:', Object.keys(commands).join(','));
node table.js
9
5
RangeError: unknown command: toString
names in the table: add,sub
The two commands computed with no if in sight. The third call is the reason for Object.hasOwn: every object inherits toString from its prototype, so a plain read of commands["toString"] would find a function that is not a command and call it with two numbers. The check asks the object for its own keys, and the error names the command that was refused. A table that can be built and extended at run time is also the reason a plugin system needs no list of the plugins anywhere in the code.
Exercises
- Put double in the table in table.js and call it through run. How many arguments does the call pass, and what does double do with the second one?
- Print operations.length and typeof operations[2] in store.js. What do the two lines say?
- Call applyTwice from pass.js with a function that returns its argument unchanged. Which number comes out, and why?
- Give makeLogger a second parameter for the punctuation and return [warn] message.. Which line of the output changes?
- Replace the table in table.js with a Map built from the same entries. What does run('toString', 1, 2) do now, and why is the guard no longer needed?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is a function in JavaScript, apart from being callable?
Answer
A value that can be stored, passed and returned like any other
A function is an object, so a binding, an array element or a property can hold it and a call may receive or return it.
-
What does the name of a function mean without parentheses after it?
Answer
The function itself, not its result
The parentheses are the call; the bare name is the value, which is why it can be passed on.
-
What does this program print?
const f = (a) => a * 2; const g = f; console.log(g(3));Answer
6
g holds the same function value, so calling g is calling f with the same argument.
-
What does this program print?
function twice(fn, v) { return fn(fn(v)); } console.log(twice((n) => n + 5, 1));Answer
11
The first call adds five and gives six, and the second adds five to that.
-
What does a higher-order function do?
Answer
It takes a function as an argument, returns one, or both
The name describes the functions it works with, not the syntax of its own definition.
-
What does this program print?
function make(n) { return () => n; } const a = make(1); const b = make(2); console.log(a(), b());Answer
1 2
Each call of make creates a closure over its own parameter, so the two returned functions keep different values.
-
What does this program print?
function f(a) { return a; } console.log(typeof f, f.length);Answer
function 1
typeof reports function for a callable value and length counts the declared parameters.
-
Why is a table of functions better than a long if-else chain?
Answer
The table is data: it can be listed, extended and passed around
A branch chain is code that must be edited, while a table can be built and extended at run time and its keys can be inspected.
-
Why does the table lookup check
Object.hasOwnbefore calling?Answer
An inherited key such as toString would return a function that is not a command
The prototype of every object supplies methods, so a plain read finds one and the call fails in a confusing place.
-
What does
sort(byLength)need from the function it is given?Answer
A number below zero, zero or above zero for a pair of items
The comparator answers which item comes first, and the array keeps the sorting algorithm itself.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev