whatstheoutput_

#80: Recursion after the outer variable is nulled

Topic: closures · Difficulty: ★

let fact = function factorial(n) {
  return n <= 1 ? 1 : n * factorial(n - 1);
};
const compute = fact;
fact = null;
console.log(compute(5));

Output

120

Why

A named function expression creates its own internal binding for its name (factorial) that lives inside the function's own closure scope, completely separate from the outer variable (fact) it happens to be assigned to. The recursive call `factorial(n - 1)` inside the body always resolves through that internal binding, which permanently points at this exact function object — it never looks up the outer fact variable at all. So even after fact is reassigned to null, compute (which still holds the original function) keeps recursing correctly and returns 5! = 120.

More closures puzzles

Play today's puzzle →