🟡 MediumFunctions📖 Theory Question

What is a Named Function Expression (NFE)?

💡

Hint

A function expression with an internal name — visible inside the body only

Full Answer

A Named Function Expression has a name after function, but unlike a declaration, the name is only visible inside the function body — not outside.

// Anonymous function expression — self-reference is fragile
const factorial = function(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1); // relies on outer var 'factorial'
};
// If factorial is reassigned, self-reference breaks!

// Named function expression — safe self-reference
const factorial = function fact(n) {
  if (n <= 1) return 1;
  return n * fact(n - 1); // 'fact' is always THIS function
};

console.log(factorial.name); // 'fact'
console.log(typeof fact);    // 'undefined' — not accessible outside!

// If outer var is reassigned, NFE still works
const f = factorial;
factorial = null;
f(5); // 120 — 'fact' still refers to itself correctly
💡 Use NFEs for recursive function expressions. Better stack traces (shows 'fact' not 'anonymous') and reliable self-reference even if the outer variable changes.

More Functions Questions

🟢 EasyWhat is the difference between call, apply, and bind?→🟢 EasyHow do arrow functions differ from regular functions?→🟢 EasyWhat is a pure function and why does it matter?→🟢 EasyWhat are Higher-Order Functions (HOF)?→

Practice this in a timed sprint →

5 free questions, no signup required

âš¡ Start Sprint