Sub topic 5
Named Function Expressions for Recursion and Debugging
A function expression can have a name of its own, separate from the variable it is assigned to. That small addition changes two things: how the function can refer to itself, and how it shows up when you are debugging. This chapter covers both, along with the scoping rules that make named function expressions behave differently from declarations.
This chapter assumes you already know how function expressions are written and assigned to variables, how const and let differ from var, and how to read a basic error stack trace in your browser or Node.js console.
The Syntax
A named function expression puts an identifier between the function keyword and the parameter list, just as a declaration does. What makes it an expression is where it appears: on the right side of an assignment, as an argument, or anywhere else a value is expected.
const factorial = function fact(n) {
return n <= 1 ? 1 : n * fact(n - 1);
};
console.log(factorial(5)); // 120
console.log(typeof fact); // "undefined"There are two names here, and they belong to different scopes:
factorialis an ordinaryconstbinding in the surrounding scope. Code outside the function uses it to call the function.factis visible only inside the function's own body. Outside,typeof factreports"undefined"because no binding with that name exists there.
A function declaration works differently. In function fact(n) { ... } written as a statement, the name fact goes into the enclosing scope. In a named function expression, the name stays inside the function.
Where the Name Lives
When the engine evaluates a named function expression, it creates a small extra scope that holds one binding: the function's name, pointing at the function itself. That scope sits between the outer scope and the function body's scope. Every call to the function gets a new body scope whose parent is this extra scope.
This structure explains three behaviors that can be surprising at first.
The name cannot be seen outside
The name scope is not part of the outer scope, so code outside the function cannot reach fact. You can reuse that name elsewhere in the file without collisions.
The name binding is read-only
You cannot reassign the inner name. In strict mode, trying to do so throws a TypeError. In sloppy mode, the assignment fails silently and the name still points at the function.
'use strict';
const f = function inner() {
try {
inner = 42;
} catch (e) {
console.log(e instanceof TypeError); // true
}
return typeof inner;
};
console.log(f()); // "function"Locals and parameters shadow the name
The body scope sits inside the name scope. A parameter or local variable with the same name therefore hides the function name.
const g = function shadow(shadow) {
return typeof shadow;
};
console.log(g(10)); // "number"Why the Inner Name Makes Recursion Safer
You might wonder why fact is needed when the function could call factorial. Calling the outer variable works, but only while that variable keeps pointing at the same function. The outer binding is shared with the rest of the program. The inner name belongs to the function alone.
The following example shows what goes wrong when the outer variable is reassigned:
let countdown = function (n) {
if (n === 0) return 'done';
return countdown(n - 1);
};
const savedA = countdown;
countdown = null;
try {
savedA(3);
} catch (e) {
console.log(e instanceof TypeError); // true: countdown is not a function
}
let countdown2 = function tick(n) {
if (n === 0) return 'done';
return tick(n - 1);
};
const savedB = countdown2;
countdown2 = null;
console.log(savedB(3)); // "done"The first version looks up countdown every time it recurses. Once that variable becomes null, the recursive call fails, even though the function itself still exists in savedA. The second version recurses through tick, which is read-only and private, so nothing outside the function can break it.
Using const for the outer variable prevents reassignment in the same scope. A named function expression still has advantages:
- The function can be copied to another variable, passed into another module, or stored on an object, and the recursion still works.
- The function can be written inline as an argument with no outer variable at all.
- The recursion does not depend on the outer variable's name, so renaming that variable cannot break it.
The replacement for arguments.callee
Older code sometimes used arguments.callee to let an anonymous function refer to itself. That property is forbidden in strict mode, which includes all class bodies and ES modules. Accessing it there throws a TypeError. A named function expression replaces it directly:
const nested = [1, [2, [3, [4]]]];
const flat = (function flatten(list) {
return list.reduce(
(acc, item) => acc.concat(Array.isArray(item) ? flatten(item) : item),
[]
);
})(nested);
console.log(flat); // [ 1, 2, 3, 4 ]Notice that the arrow function passed to reduce can see flatten too. Any function defined inside the body can use the name, because the name scope is part of its scope chain.
Self-Referencing Callbacks
Recursion is not the only reason a function needs to refer to itself. A common case is an event listener that removes itself after it runs. removeEventListener needs a reference to the exact same function object, and an inline named expression provides one without declaring a variable first. This example uses EventTarget, which is available in browsers and in Node.js 15 and later:
const target = new EventTarget();
let calls = 0;
target.addEventListener('ping', function onFirstPing() {
calls += 1;
target.removeEventListener('ping', onFirstPing);
});
target.dispatchEvent(new Event('ping'));
target.dispatchEvent(new Event('ping'));
console.log(calls); // 1The same pattern works for a setTimeout loop that schedules itself again:
let ticks = 0;
setTimeout(function poll() {
ticks += 1;
console.log('tick', ticks);
if (ticks < 3) setTimeout(poll, 10);
}, 10);
// tick 1
// tick 2
// tick 3Names for Debugging
Every function has a name property, and debuggers, profilers, and stack traces display it. An anonymous function shows up as <anonymous> or a blank entry. That gives you little to work with when an error is thrown from somewhere inside a chain of callbacks.
Since ES2015, engines infer a name for many anonymous functions from the syntax around them. Inference only happens in certain positions, though, so you need to know where it applies.
const save = function () {};
const obj = { load: function () {} };
const handlers = [function () {}, function onSubmit() {}];
const named = function realName() {};
function run(cb) {
return cb.name;
}
console.log(save.name); // "save"
console.log(obj.load.name); // "load"
console.log(handlers.map((h) => h.name)); // [ '', 'onSubmit' ]
console.log(run(function () {})); // ""
console.log(run(function validate() {})); // "validate"
console.log(named.name); // "realName"| Where the function appears | Inferred `name` | Inner binding for self-reference |
|---|---|---|
| `const x = function () {}` | `"x"` | No |
| `{ key: function () {} }` | `"key"` | No |
| `const x = () => {}` | `"x"` | No |
| Array element | `""` | No |
| Argument to another function | `""` | No |
| `function realName() {}` in any position | `"realName"` | Yes |
The table shows the practical rule. Functions passed directly as arguments, such as callbacks to map, then, addEventListener, or a test runner, get no inferred name. Those are the functions that most often appear in stack traces, so they benefit most from an explicit name. In V8, for example, an error thrown inside run(function validate() { ... }) produces a stack line beginning at validate, while the anonymous version shows at <anonymous> or only a file position.
Arrow Functions Cannot Do This
Arrow functions have no syntax for an inner name. An arrow can get an inferred name from a variable or property, but it can only refer to itself through some outer binding. A recursive arrow therefore depends on the variable it is assigned to:
const fib = (n) => (n < 2 ? n : fib(n - 1) + fib(n - 2));
console.log(fib(10)); // 55This works fine when fib is a const that never leaves its module. If you need an inline recursive callback, or a function that keeps working after it is copied elsewhere, use a named function expression.
A Historical Note
Very old versions of Internet Explorer (JScript in IE8 and earlier) leaked the names of named function expressions into the enclosing scope and sometimes created two separate function objects. Old style guides warned against named function expressions for this reason. Every modern engine follows the specification, so the warning no longer applies.
Exercise
What does this code print, and why? const a = function b() { return typeof b; }; console.log(a(), typeof b);
Show answer
It prints "function undefined". Inside the body, b refers to the function through the private name scope, so typeof b is "function". Outside, b was never added to the enclosing scope, so typeof b is "undefined".
Exercise
A teammate writes let sum = function (list) { return list.length ? list[0] + sum(list.slice(1)) : 0; }; and later another module does const total = sum; sum = undefined; total([1, 2, 3]);. What happens, and how do you fix it with the smallest change?
Show answer
The call throws a TypeError, because the recursive call looks up the outer variable sum, which is now undefined. Give the expression an inner name and recurse through it: let sum = function sumList(list) { return list.length ? list[0] + sumList(list.slice(1)) : 0; };. Then total([1, 2, 3]) returns 6 no matter what happens to sum.
Exercise
Why does function walk(walk) { return walk(1); } written as a named function expression fail when called with a number, and what does [() => {}].map(f => f.name) return?
Show answer
The parameter walk shadows the function's own name, so walk(1) tries to call the number argument and throws a TypeError. The map returns [ '' ], because an arrow function inside an array literal gets no inferred name.