Sub topic 2
Functions as Values
This chapter assumes you know core JavaScript syntax, arrow functions, spread and rest syntax, and basic scoping rules. You should also be able to run code in Node.js or a browser console. Every example below runs as shown in Node 18 or later.
In JavaScript, a function is a value, just like a number, a string, or an object. You can store it in a variable, put it in an array, pass it to another function, and return it from a function. Languages that allow this are said to have first-class functions. Everything else in this tutorial depends on this property: closures, higher-order functions, composition, and currying all assume that functions can be handled like ordinary data.
The Working Model: A Function Is an Object You Can Call
A function in JavaScript is a special kind of object. It has properties, it can be referenced by several names, and it has one extra ability: you can invoke it with (). The name you give a function is a variable that holds a reference to that object. It is not the function itself.
function greet(name) {
return `Hello, ${name}`;
}
const sayHi = greet; // copy the reference, do not call
console.log(sayHi('Ada')); // Hello, Ada
console.log(sayHi === greet); // true: both names point to one object
console.log(typeof greet); // function
console.log(greet instanceof Object); // trueThe line const sayHi = greet has no parentheses, so nothing runs. It copies a reference, the same way const b = a copies a reference to an object.
Four Things You Can Do With a Function Value
Store it in a variable
Function expressions and arrow functions are values that you assign right away:
const square = function (x) { return x * x; };
const cube = (x) => x * x * x;
console.log(square(4), cube(3)); // 16 27Store it in a data structure
Putting functions in objects or maps gives you a dispatch table. It replaces long switch statements with a lookup.
const operations = {
add: (a, b) => a + b,
sub: (a, b) => a - b,
mul: (a, b) => a * b,
div: (a, b) => a / b
};
const calculate = (op, a, b) => {
const fn = operations[op];
if (typeof fn !== 'function') throw new Error(`Unknown op: ${op}`);
return fn(a, b);
};
console.log(calculate('mul', 6, 7)); // 42
const steps = [(x) => x + 1, (x) => x * 2, (x) => x - 3];
let value = 5;
for (const step of steps) value = step(value);
console.log(value); // 9Adding a new operation is now a data change, so the control flow stays the same. The typeof fn !== 'function' guard matters: looking up a missing key returns undefined, and calling undefined throws a less helpful TypeError.
Pass it as an argument
A function that receives another function can leave part of its behavior to the caller:
const applyTwice = (fn, x) => fn(fn(x));
console.log(applyTwice((n) => n + 10, 1)); // 21
console.log(applyTwice((s) => s + '!', 'hey')); // hey!!Return it from a function
A function can build and return a new function:
const makeMultiplier = (factor) => (n) => n * factor;
const triple = makeMultiplier(3);
console.log(triple(7)); // 21The returned function still sees factor after makeMultiplier has finished. That is a closure, which the next chapter covers. Functions that take or return functions are higher-order functions, and they get their own chapter later.
Ways to Create a Function Value
The three common syntaxes all produce function objects, but they behave differently in ways that matter once you start passing them around.
| Form | Example | Hoisted | Own `this` | Usable with `new` |
|---|---|---|---|---|
| Declaration | `function f() {}` | Yes, fully | Yes, dynamic | Yes |
| Expression | `const f = function () {}` | Variable only (TDZ for `const`) | Yes, dynamic | Yes |
| Arrow | `const f = () => {}` | Variable only (TDZ for `const`) | No, uses enclosing `this` | No |
A declaration can be called before the line where it appears. A const expression cannot, because the variable sits in the temporal dead zone (TDZ) until that line runs:
console.log(early(2)); // 4: declarations are hoisted
function early(x) { return x * 2; }
try {
late(2);
} catch (e) {
console.log(e.constructor.name); // ReferenceError
}
const late = (x) => x * 2;Function Objects Have Properties
Since functions are objects, they carry metadata. Two built-in properties are useful: name and length.
const add = (a, b) => a + b;
const withDefault = (a, b = 1) => a + b;
const variadic = (...args) => args.length;
console.log(add.name, add.length); // add 2
console.log(withDefault.length); // 1: counting stops at the first default
console.log(variadic.length); // 0: rest parameters are not counted
add.calls = 0; // you can attach your own properties too
console.log(Object.keys(add)); // [ 'calls' ]length is the function's declared arity, meaning the number of parameters it expects. The currying chapter builds a generic curry helper that depends on fn.length. Default and rest parameters reduce length, so a curried function with defaults can run earlier than you expect.
Common Errors
Calling instead of passing
The most frequent mistake is adding parentheses where a reference was wanted. With fn() you pass the function's result, and with fn you pass the function.
const log = () => console.log('tick');
setTimeout(log, 100); // correct: passes the function
// setTimeout(log(), 100); // wrong: runs now, passes undefined
const items = [1, 2, 3];
const double = (x) => x * 2;
console.log(items.map(double)); // [ 2, 4, 6 ]If you need to pass arguments, wrap the call: setTimeout(() => log('a'), 100).
Losing `this` when extracting a method
When you take a method off an object, you get the bare function. The connection to the object is lost, because regular functions decide this at call time based on how they are called.
'use strict';
const counter = {
count: 0,
increment() {
this.count += 1;
return this.count;
}
};
const inc = counter.increment;
try {
inc();
} catch (e) {
console.log(e.constructor.name); // TypeError: this is undefined
}
const bound = counter.increment.bind(counter);
console.log(bound()); // 1
const wrapped = () => counter.increment();
console.log(wrapped()); // 2Without strict mode, this would point to the global object and the code would quietly write a count property onto it. Either fix works: bind creates a new function with this fixed, and the arrow wrapper calls the method on the object every time.
Passing a function with the wrong signature
When you pass a function as a value, the receiver decides which arguments it gets. Array.prototype.map calls its callback with (element, index, array). parseInt accepts (string, radix), so the index ends up as the radix:
console.log(['10', '10', '10'].map(parseInt));
// [ 10, NaN, 2 ]: parseInt('10', 0), parseInt('10', 1), parseInt('10', 2)
console.log(['10', '10', '10'].map((s) => parseInt(s, 10))); // [ 10, 10, 10 ]
console.log(['10', '10', '10'].map(Number)); // [ 10, 10, 10 ]Edge Cases Worth Knowing
- Equality is by reference. Two functions with identical source code are not equal:
(() => 1) === (() => 1)isfalse. This matters when you try to remove an event listener with a fresh arrow function. Removal fails silently because the reference differs from the one you added. - Functions are not serializable.
JSON.stringify({ f: () => 1 })produces"{}". Data structures that hold functions cannot be sent over the network or stored as JSON. - Arrow functions have no
argumentsobject and noprototype. Use rest parameters instead ofarguments. - Checking for a function:
typeof x === 'function'is the reliable test. It also returnstruefor classes and async functions.
Exercise
The code const btn = { label: 'Save', click() { return this.label; } }; const handlers = [btn.click]; console.log(handlers[0]()); does not print "Save" in strict mode. Explain why, and give two ways to fix it.
Show answer
Calling handlers[0]() invokes the function with handlers as the receiver, not btn, so this is the array and this.label is undefined. When a bare reference is called, this is undefined in strict mode. Fix it by storing a bound copy, btn.click.bind(btn), or by storing a wrapper, () => btn.click(), which always calls the method on btn.
Exercise
Write a dispatch table formatters with keys upper, lower, and title (capitalize the first letter of each word). Then write format(kind, text) that applies the matching formatter and returns the text unchanged if the kind is unknown. What does format('title', 'hello big world') return?
Show answer
One solution: const formatters = { upper: (s) => s.toUpperCase(), lower: (s) => s.toLowerCase(), title: (s) => s.split(' ').map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(' ') }; const format = (kind, text) => (formatters[kind] ?? ((s) => s))(text); The call returns "Hello Big World". The ?? ((s) => s) fallback is itself a function value used in place of a missing entry.
Exercise
What are the values of fnA.length and fnB.length for const fnA = (a, b, c = 0) => a + b + c; and const fnB = (a, ...rest) => a;, and why might this matter for a generic curry helper?
Show answer
fnA.length is 2, because counting stops at the first parameter with a default. fnB.length is 1, because rest parameters are not counted. A curry helper that uses fn.length would call fnA after two arguments, never waiting for c, and would call fnB after one argument.