Sub topic 5
Defaults Are Evaluated on Every Call
This chapter assumes you can declare and call functions, write a basic default parameter such as name = "guest", and know that defaults apply only when an argument is undefined. Here we look at when a default expression runs. It runs each time the function is called without that argument, and it does not run when the argument is supplied. This rule explains why JavaScript has no "shared mutable default" bug. It also explains why a default can pick up surprising values from the code around it.
The rule: a fresh evaluation per call
A default value is an expression, and JavaScript does not store it as a fixed value. When a call starts, the engine binds the parameters from left to right. For each parameter whose argument is undefined, it evaluates the default expression at that moment and binds the result.
The clearest consequence shows up with object and array defaults:
function append(item, list = []) {
list.push(item);
return list;
}
const first = append(1);
const second = append(2);
console.log(first); // [1]
console.log(second); // [2]
console.log(first === second); // false: two different arraysEach call that omits list runs [] again and gets a brand-new array. Pushing into it cannot affect any other call.
Contrast with languages that evaluate once
If you have used Python, you may know its classic trap. Python evaluates def f(x, items=[]) a single time, when the function is defined, so every call shares the same list. JavaScript does not work this way.
| Language | When the default is evaluated | Mutable default shared across calls? |
|---|---|---|
| JavaScript | At each call where the argument is `undefined` | No |
| Python | Once, when `def` runs | Yes |
| C++ | At each call site that omits the argument | No |
| Ruby | At each call that omits the argument | No |
Defaults are lazy: skipped when an argument is given
When you pass a value, the default expression is not evaluated at all. Any side effects in it, such as function calls, counters, or logging, do not happen.
let idCalls = 0;
function makeId() {
idCalls += 1;
return `id-${idCalls}`;
}
function createRecord(name, id = makeId()) {
return { name, id };
}
console.log(createRecord("a")); // { name: 'a', id: 'id-1' }
console.log(createRecord("b", "custom")); // { name: 'b', id: 'custom' }
console.log(createRecord("c")); // { name: 'c', id: 'id-2' }
console.log(idCalls); // 2makeId() ran twice, only for the calls that omitted id. Because of this, an expensive default is safe for callers who supply the value. Callers who omit it pay the cost on every call, and the result is never cached.
Time-dependent defaults
Call-time evaluation makes defaults like "now" work as you would expect:
function logEvent(message, at = new Date().toISOString()) {
return `[${at}] ${message}`;
}
console.log(logEvent("started"));
setTimeout(() => console.log(logEvent("finished")), 1000);
// The two timestamps differ by about one second.If the default were evaluated once, every event would carry the time the function was defined.
Outer variables are read when the call happens
A default expression can refer to variables outside the function. It reads their current value at call time. It does not read the value they held when the function was declared.
let defaultCurrency = "USD";
function formatPrice(amount, currency = defaultCurrency) {
return `${amount.toFixed(2)} ${currency}`;
}
console.log(formatPrice(5)); // "5.00 USD"
defaultCurrency = "EUR";
console.log(formatPrice(5)); // "5.00 EUR"Sometimes this is what you want, for example a configurable module-level setting. It becomes a bug when you expected the default to be fixed. If the value must not change, declare it with const, or put a literal directly in the default.
Sharing an object on purpose
Sometimes you do want every call to use the same object, such as a cache. Create the object once outside the function and use its name as the default:
const sharedCache = new Map();
function lookup(key, cache = sharedCache) {
if (!cache.has(key)) {
cache.set(key, key.toUpperCase());
}
return cache.get(key);
}
lookup("a");
lookup("b");
console.log(sharedCache.size); // 2: both calls used the same Map
const isolated = new Map();
lookup("c", isolated);
console.log(sharedCache.size); // still 2The expression sharedCache is still evaluated on every call. It produces the same reference each time, so the calls share the object. The code states the sharing openly, so a reader is not caught by surprise.
Evaluation order and side effects
Defaults are evaluated strictly from left to right, and only for the parameters that need them:
const order = [];
function trace(label, value) {
order.push(label);
return value;
}
function f(a = trace("a", 1), b = trace("b", 2), c = trace("c", 3)) {
return [a, b, c];
}
console.log(f(undefined, 20)); // [1, 20, 3]
console.log(order); // ["a", "c"]Because the order is fixed, a later default can use an earlier parameter. The next chapter covers that. The order also makes side effects in defaults predictable, though they are still easy to miss when reading a signature. Keep defaults to cheap, pure expressions, or calls with an obvious purpose such as makeId().
Common errors
| Mistake | What actually happens | Fix |
|---|---|---|
| Expecting `list = []` to persist between calls | Each call gets a new array | Pass the array in, or use an outer variable on purpose |
| Assuming a default captures an outer value at definition time | The default reads the variable's current value | Use `const` or a literal |
| Putting heavy work in a default and calling without the argument in a loop | The work repeats on every call | Compute the value once and pass it in |
| Hiding important side effects (logging, I/O) in a default | Side effects run only on some calls, which is hard to see | Move them into the function body |
| Passing `null` to "trigger" the default | `null` is bound, so the default does not run | Pass `undefined` or omit the argument |
Exercise
What does this program print, and why? let count = 0; function tick(step = ++count) { return step; } console.log(tick(), tick(10), tick(), count);
Show answer
It prints "1 10 2 2". The first call omits step, so ++count runs and returns 1. The second call passes 10, so the default is skipped and count stays at 1. The third call evaluates the default again and returns 2. By the time count is read, it is 2.
Exercise
A teammate writes function addTag(tag, tags = []) { tags.push(tag); return tags; } and worries that repeated calls of addTag("x") will build up ["x", "x", ...]. Are they right? What change would make all calls without a second argument share one array?
Show answer
They are not right. The expression [] is evaluated on every call that omits tags, so each call returns a new one-element array. To share one array, create it once outside the function (const allTags = [];) and write tags = allTags. The default expression then evaluates to the same reference every time.
Exercise
Given let unit = "cm"; function size(n, u = unit) { return n + u; } then unit = "in"; what does size(3) return, and how would you make the default always be "cm"?
Show answer
It returns "3in", because the default reads unit when the call happens, and unit is "in" by then. To fix the default at "cm", write u = "cm" directly, or declare the outer value with const so it cannot be reassigned.