JavaScript · Lesson 3
Functions and Closures
Functions are values you can pass, return and store, and every function remembers the variables around it; that one idea gives you private state, factories, once, memoize, curry and pipe.
In short
- Functions are values: pass them, return them, store them
- A closure is a function plus the variables it was created with
- Each call makes a new scope, so factories give independent state
- Closures capture variables, not values: use
letin loops - Wrappers like
onceandmemoizekeep their state in a closure
In JavaScript a function is a value, just like a number or an object. You can store it in a variable, put it in an array, pass it to another function and return it from one. And every function carries a hidden link to the variables that were in scope where it was created. That pair (a function plus the variables it can still see) is a closure.
Those two ideas explain most of what makes JavaScript code look the way it does: callbacks, event handlers, React hooks, middleware, debounce, memoize and the "module pattern". This lesson builds the mental model, then the exercises turn it into utilities you'll write (or debug) at work.
Every js snippet has a ▶ Try button. Predict the output, then run it. Snippets run in strict mode,
like an ES module.
Three ways to make a function
// 1. Declaration: hoisted, so you can call it above the line where it's written
console.log(square(4));
function square(n) {
return n * n;
}
// 2. Expression: a function value assigned to a variable
const cube = function (n) {
return n * n * n;
};
// 3. Arrow function: shorter, and the body can be a single expression
const double = (n) => n * 2;
console.log(cube(2), double(5));
| Declaration | Expression | Arrow | |
|---|---|---|---|
| Hoisted (callable before its line) | yes, with its body | no (the variable is in the TDZ, or undefined with var) | no |
Own arguments object | yes | yes | no, it sees the outer function's |
Can be called with new | yes | yes | no, TypeError |
Own this | yes | yes | no, it uses the outer this |
The last row is the big one, and the How this Works topic covers it. For this topic, the rule of thumb is: use arrow functions for callbacks and small helpers, and declarations for named, top-level functions.
Two arrow function details trip people up:
const toUser = (name) => ({ name, active: true }); // parentheses: an object, not a block
const broken = (name) => { name: name }; // a block with a label, returns undefined
console.log(toUser('ann').name);
console.log(broken('ann'));
A named function expression can call itself by its own name, and that name doesn't leak outside:
const factorial = function fact(n) {
return n <= 1 ? 1 : n * fact(n - 1);
};
console.log(factorial(5));
console.log(typeof fact); // the name only exists inside the function
Parameters
JavaScript doesn't check how many arguments you pass. Missing ones are undefined, and extra ones are
ignored (but still reachable).
function greet(name, greeting = 'Hello') {
return `${greeting}, ${name}!`;
}
console.log(greet('Ann')); // default used
console.log(greet('Ann', undefined)); // undefined also triggers the default
console.log(greet('Ann', null)); // null does NOT
console.log(greet('Ann', 'Hi', 'extra')); // extra argument ignored
Default values have three properties worth knowing:
- They apply only when the argument is
undefined, never fornull,0or''. - They're evaluated on every call, so
list = []gives a fresh array each time. (Python programmers expect the opposite.) - They can use earlier parameters:
function range(start, end = start + 10).
Rest parameters collect the remaining arguments into a real array. Spread does the reverse at the call site:
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
const values = [1, 2, 3];
console.log(sum(...values, 4));
console.log(Math.max(...values));
The arguments object is the old way. It's array-like (it has length and indexes, but no
map or reduce), arrow functions don't have their own, and in strict mode it's no longer linked to
the named parameters. Prefer rest parameters in new code. You'll still meet arguments in older
libraries and in interview questions:
function oldStyle() {
console.log(arguments.length, Array.isArray(arguments));
return Array.from(arguments).join('-');
}
console.log(oldStyle('a', 'b', 'c'));
A function's length is the number of parameters before the first default or rest parameter.
Libraries such as curry rely on it:
console.log(((a, b, c) => {}).length); // 3
console.log(((a, b = 2, c) => {}).length); // 1
console.log(((...all) => {}).length); // 0
The classic: map(parseInt)
console.log(['1', '2', '3'].map(parseInt));
map calls its callback with three arguments: (value, index, array). parseInt takes two:
(string, radix). So this calls parseInt('1', 0), parseInt('2', 1) and parseInt('3', 2), and you
get [1, NaN, NaN]. When you pass a function you didn't write as a callback, wrap it so you control
the arguments: strings.map((s) => parseInt(s, 10)) or strings.map(Number).
Functions are values
Because functions are values, a function can take functions or return them. That's a
higher-order function. You already use them every day: map, filter, addEventListener,
setTimeout, Promise.then.
const isEven = (n) => n % 2 === 0;
const not = (predicate) => (value) => !predicate(value); // takes a function, returns a function
const isOdd = not(isEven);
console.log([1, 2, 3, 4].filter(isOdd));
// functions are objects, so they have properties too
console.log(isEven.name, isEven.length);
Look at not: it returns a new function that still uses predicate long after not itself returned.
That's a closure doing its job.
Closures
When a function is created, it keeps a reference to the scope it was created in. Calling it later can read and write those variables, even after the outer function has returned.
function createCounter() {
let count = 0; // private: nothing outside can touch it directly
return {
increment: () => ++count,
current: () => count,
};
}
const a = createCounter();
const b = createCounter();
a.increment();
a.increment();
b.increment();
console.log(a.current(), b.current()); // each call made a new `count`
console.log(a.count); // not reachable from outside
Three things to notice:
- Every call to
createCountercreates a new scope.aandbhave separatecountvariables. That's how factories work. - The variable is private. The only way to change
countis through the functions you returned. Before#privateclass fields existed, this was the way to hide state, and it still is in function-based code (React hooks are built on it). - A closure captures the variable, not a copy of its value. If the variable changes later, the closure sees the new value.
let label = 'draft';
const show = () => console.log('label is', label);
label = 'published';
show(); // reads the variable when it runs, not when it was created
The loop gotcha
This is probably the most-asked closure question in interviews:
const withVar = [];
for (var i = 0; i < 3; i++) withVar.push(() => i);
const withLet = [];
for (let j = 0; j < 3; j++) withLet.push(() => j);
console.log(withVar.map((f) => f())); // [3, 3, 3]
console.log(withLet.map((f) => f())); // [0, 1, 2]
var is function-scoped, so there's one i shared by all three closures, and by the time they
run it's 3. let in a for loop creates a fresh binding for every iteration, so each closure
gets its own j. Use let and const, and this bug disappears. (C# had the same bug with foreach
until C# 5 changed the loop variable to be per-iteration.)
Stale closures
The flip side of "closures see the variable" is that each closure sees the variable from its own scope. When a scope is created again (a React component re-renders, a function is called again), old closures still point at the old variables:
function render(count) {
// imagine this is a React component; each render is a new call with a new `count`
const logLater = () => console.log('clicked when count was', count);
return logLater;
}
const handlerFromFirstRender = render(1);
render(2); // a new render creates a new closure, but nobody updated the old one
handlerFromFirstRender();
That's the "stale closure" behind many React bugs: an interval or event handler created in the first
render keeps reading the first render's state. The fixes are functional updates
(setCount((c) => c + 1)), correct effect dependencies, or a ref.
Closures keep things alive
A closure keeps its whole scope reachable, so the garbage collector can't free it. A long-lived
callback (an event listener on window, a cache, a timer that's never cleared) that closes over a large
object keeps that object in memory. Remove listeners and clear timers when you're done, and don't
close over more than you need.
Patterns built on closures
Each of these is a function that takes a function and returns a new function with extra behaviour, keeping its state in the closure. The exercises have you build complete versions.
once
function once(fn) {
let done = false;
let result;
return (...args) => {
if (!done) {
done = true;
result = fn(...args);
}
return result;
};
}
const init = once(() => {
console.log('connecting...');
return 'connection';
});
console.log(init(), init()); // connects only once
memoize
Cache results by argument, so an expensive pure function only computes each answer once:
function memoize(fn) {
const cache = new Map();
return (n) => {
if (!cache.has(n)) cache.set(n, fn(n));
return cache.get(n);
};
}
let calls = 0;
const slowSquare = (n) => {
calls++;
return n * n;
};
const fastSquare = memoize(slowSquare);
fastSquare(9);
fastSquare(9);
console.log(fastSquare(9), 'computed', calls, 'time(s)');
cache.has (not cache.get(n) !== undefined) matters: a function can legitimately return undefined.
Real memoizers also need a way to build a key from several arguments, and a size limit, or the cache
becomes a memory leak.
Currying and partial application
Partial application fixes some arguments now and the rest later. Currying turns a function of several arguments into a chain of one-argument functions.
const add3 = (a, b, c) => a + b + c;
// partial application: fix the first argument
const addTen = (b, c) => add3(10, b, c);
// manual currying
const curriedAdd = (a) => (b) => (c) => a + b + c;
console.log(addTen(1, 2), curriedAdd(1)(2)(3));
// a real use: configure once, use many times
const log = (level) => (message) => console.log(`[${level}] ${message}`);
const warn = log('warn');
warn('disk almost full');
F# curries every function automatically. JavaScript doesn't, so a generic curry(fn) uses fn.length
to know how many arguments to wait for. You'll build one.
compose and pipe
pipe(f, g, h)(x) means h(g(f(x))): data flows left to right. compose is the same thing in
mathematical order, right to left.
const pipe = (...fns) => (input) => fns.reduce((value, fn) => fn(value), input);
const slugify = pipe(
(s) => s.trim(),
(s) => s.toLowerCase(),
(s) => s.replace(/[^a-z0-9]+/g, '-'),
);
console.log(slugify(' Hello World, Again '));
You've seen this shape in Redux middleware (compose), RxJS (.pipe(...)), Express middleware and
the F# |> operator.
Pure functions
A pure function returns the same output for the same input and has no side effects: no mutation of its arguments or outside variables, no I/O, no reading the clock or random numbers.
// impure: mutates the caller's array and depends on outside state
let taxRate = 0.2;
function addTaxImpure(prices) {
for (let i = 0; i < prices.length; i++) prices[i] *= 1 + taxRate;
return prices;
}
// pure: new array, everything it needs comes in as arguments
const addTax = (prices, rate) => prices.map((p) => p * (1 + rate));
const original = [10, 20];
console.log(addTax(original, 0.5), original);
addTaxImpure(original);
console.log(original); // the caller's data changed under them
Purity is what makes memoize safe (an impure function's cached answer can be wrong), what React expects
from components and reducers, and what makes code easy to test. Real programs need side effects, so the
practical goal is to push them to the edges and keep the logic in the middle pure.
Gotchas people actually hit
- Calling instead of passing.
button.addEventListener('click', save())callssaveright now and registers its return value. Pass the function:addEventListener('click', save), or wrap it:() => save(id). - Callbacks get more arguments than you think.
map(parseInt), oritems.forEach(console.log)printing indexes too. - Default parameters and
null. An API that sendsnulldoesn't trigger your default. - Shared state in a closure. A cache or counter created at module level is shared by every caller (and every test). Create it inside a factory if each user needs its own.
- Recreating closures by accident. A
memoize(fn)ordebounce(fn)called inside a function that runs often (like a React render) creates a new, empty wrapper each time, so nothing is cached or debounced. Create the wrapper once.
Coming from C# or TypeScript
Side note
- C# lambdas are closures too, with the same capture-the-variable rule.
Func<int, int>is just a function value in JavaScript, with no delegate types to declare. - C# overloads and checks the argument count. JavaScript does neither: there's one function, and you
handle missing arguments with defaults or
undefinedchecks. - TypeScript adds types on top of exactly these runtime rules. A
(...args: unknown[]) => voidparameter is still a plain function at runtime, andfn.lengthstill ignores defaults and rest.
In real codebases
Side note
- React is closures all the way down. Every render creates new handler functions that close over
that render's props and state, and
useCallback/useMemoexist to keep the same closure between renders when that matters. - Middleware (Express, Redux, Koa) is higher-order functions:
(store) => (next) => (action) => ...is a curried function. - Utilities like lodash's
once,memoize,debounce,throttleandcurryare exactly the wrappers in this topic. Knowing how they work tells you when they'll surprise you (shared caches, wrappers recreated on every render). - Configuration factories:
createApiClient({ baseUrl, token })returning functions that use those values is cleaner than passing the same options to every call.
The exercises
- Counter factory (easy): private state in a closure, one scope per call.
- once (easy): run initialisation at most once, and retry if it failed.
- pipe and compose (medium): build functions out of functions.
- curry (medium): wait for enough arguments, in any grouping, using
fn.length. - A tiny store with subscribe (medium): private state, listeners and unsubscribe closures, like Redux.
- memoize with a key resolver and a size limit (hard): a least-recently-used cache in a closure.
- Rate-limited function (hard): at most N calls per time window, with a queue, timers and cleanup.
The next topic, How this Works, covers the one thing closures don't capture: this.
Practise this lesson
In the app: a short video, 7 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.
Open in the app