Sub topic 5
Named Function Expressions for Recursion and Debugging
This chapter assumes you know how function expressions work and how const and let bindings behave. In the previous chapter, the function expressions were anonymous. You can also give a function expression its own name. That name behaves differently from the variable that holds the function, and the difference is useful in two places: recursion and debugging.
The Name Lives Inside the Function
A named function expression puts a name between function and the parameter list. That name is bound only inside the function's own body. Code outside the function cannot see it.
const factorial = function fact(n) {
return n <= 1 ? 1 : n * fact(n - 1);
};
console.log(factorial(5)); // 120
console.log(typeof fact); // "undefined"Here there are two names. factorial is the outer variable, and callers use it. fact is the inner name, and only the function body can use it. The inner name doesn't leak into the surrounding scope, so it can't collide with other code.
Why Recursion Should Use the Inner Name
A recursive function that calls itself through the outer variable depends on that variable. If the variable is reassigned, the recursion breaks.
let countdown = function (n) {
return n <= 0 ? 'done' : countdown(n - 1);
};
const saved = countdown;
countdown = null;
try {
saved(3);
} catch (e) {
console.log(e instanceof TypeError); // true: countdown is not a function
}If the function calls itself by its inner name, it keeps working wherever the function object ends up:
let countdown = function tick(n) {
return n <= 0 ? 'done' : tick(n - 1);
};
const saved = countdown;
countdown = null;
console.log(saved(3)); // doneThe inner name tick always refers to this exact function, so outside reassignments can't affect it.
Clearer Stack Traces
Every function has a name property, and debuggers and stack traces use it. When you assign an anonymous function to a variable, JavaScript infers the name from the variable:
const handler = function () {};
console.log(handler.name); // "handler"
const named = function onClick() {};
console.log(named.name); // "onClick"
console.log([function () {}][0].name); // ""Name inference only applies to assignments and similar patterns. When you pass an anonymous function inline to another function, nothing gives it a name, and stack traces show it as <anonymous>. Giving inline callbacks a name makes errors easier to trace:
setTimeout(function retryUpload() {
throw new Error('upload failed');
}, 0);
// The stack trace lists "retryUpload" instead of an anonymous frameA named callback can also call itself, which suits retries and polling loops:
let attempts = 0;
setTimeout(function poll() {
attempts += 1;
console.log('attempt', attempts);
if (attempts < 3) setTimeout(poll, 0);
}, 0);
// attempt 1, attempt 2, attempt 3Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Calling the inner name from outside | ReferenceError, because the name is not in scope | Call through the outer variable |
| Recursing through the outer variable | Breaks if the variable is reassigned | Recurse through the inner name |
| Assigning to the inner name | Ignored, or TypeError in strict mode | Use a separate local variable |
| Expecting arrows to take an inner name | Syntax error, because arrows cannot be named this way | Use a named function expression |
Exercise
Given const walk = function visit(node) { if (node.child) visit(node.child); return node.id; };, what do typeof visit (run outside the function) and walk.name evaluate to, and why does the recursion still work if walk is later copied to another variable and the original variable is no longer used?
Show answer
typeof visit is "undefined" because the inner name is only bound inside the function body. walk.name is "visit" because an explicit name takes priority over the inferred one. The recursion keeps working because visit always refers to the function object itself, not to whatever variable holds it.
Exercise
Rewrite [3, 2, 1].forEach(function () { console.log(missing.value); }); so that the resulting error's stack trace identifies the callback by name.
Show answer
Give the callback a name, for example [3, 2, 1].forEach(function logValue() { console.log(missing.value); });. The ReferenceError's stack trace will then show a frame named logValue instead of an anonymous one.