Course contentsShow
← JavaScript
Lesson 383 of 2,72311. FunctionsFree lesson

Named Function Expressions

Understand function expressions with names and when to use them for debugging.

Named Function Expressions

What you'll learn: How giving your function expressions a name can help you debug and understand your code better.

What's the Difference?

You already know about anonymous function expressions — functions assigned to variables without their own name:

const greet = function() {
  return "Hello!";
};

A named function expression gives the function its own name inside the expression:

const greet = function sayHello() {
  return "Hello!";
};

Notice sayHello is the function's internal name, while greet is the variable name.

Why Does This Matter?

Better stack traces: When an error occurs, the function's name appears in error messages instead of "anonymous function," making debugging much easier.

const calculate = function processData(x) {
  if (x < 0) throw new Error("Negative value");
  return x * 2;
};

calculate(-5); // Error will show "processData" in stack trace

Self-reference: The function can reference itself by name (useful for recursion, though you haven't learned that pattern yet):

const countdown = function count(n) {
  console.log(n);
  if (n > 0) count(n - 1); // Function calls itself by name
};

countdown(3); // logs: 3, 2, 1, 0

Important: The Name is Internal Only

The internal name (sayHello) is only available inside the function body. Outside, you must use the variable name:

const greet = function sayHello() {
  return "Hello!";
};

greet(); // ✓ Works
sayHello(); // ✗ Error: sayHello is not defined

Key Takeaway: Named function expressions improve debugging with clearer stack traces and allow internal self-reference, while keeping the name scoped within the function itself.