The main difference between a function declaration (function fn() {}) and a function expression (var fn = function() {} or const fn = function() {}) is hoisting behavior, declaration scope/binding rules (var vs. let/const), and named vs. anonymous function identity (including TDZ / ReferenceError vs. TypeError when called before initialization). A function declaration is hoisted with both its name and its function body available in its enclosing scope, whereas a function expression is only evaluated at runtime when execution reaches the assignment—meaning calling var fn = function() {} before assignment throws TypeError: fn is not a function (because var fn is hoisted as undefined), while calling const fn = function() {} before assignment throws ReferenceError due to the Temporal Dead Zone (TDZ).
1. Hoisting, TDZ, and Error Behavior Before Assignment
Compare how a function declaration, a var function expression, and a const function expression behave when invoked above the line where they appear:
// 1. Function declaration: both identifier and body are hoisted
console.log(declaredGreeting("Ali")); // "Hello, Ali"
function declaredGreeting(name) {
return `Hello, ${name}`;
}
// 2. `var` function expression: `var` binding is hoisted as `undefined`
// Calling before assignment throws: TypeError: varGreeting is not a function
try {
console.log(varGreeting("Ali"));
} catch (error) {
console.error(`${error.name}: ${error.message}`); // TypeError
}
var varGreeting = function (name) {
return `Hello, ${name}`;
};
// 3. `const` function expression: block-scoped and subject to TDZ before declaration
// Calling before declaration throws: ReferenceError
try {
console.log(constGreeting("Ali"));
} catch (error) {
console.error(`${error.name}: ${error.message}`); // ReferenceError
}
const constGreeting = function (name) {
return `Hello, ${name}`;
};
- Function declarations support top-down readability: Helper functions can appear below main logic in the same scope without failing when called earlier.
- Prefer
constovervarfor function expressions:constprevents accidental re-assignment or accidentalundefinedinvocation before initialization.
2. Named Function Expressions, Recursion, and Stack Traces
A function expression can be anonymous (const f = function() {}) or named (const factorial = function calc(n) { ... }). Naming a function expression gives a local binding visible only inside the function body (useful for clean recursion even if the outer const variable is reassigned) and improves call stacks and debugging over older anonymous expressions:
// Named function expression: internal name `step` stays available for recursion
const countdown = function step(remaining) {
if (typeof remaining !== "number" || !Number.isInteger(remaining) || remaining < 0) {
throw new RangeError("Expected a non-negative integer.");
}
if (remaining === 0) {
return ["done"];
}
return [remaining, ...step(remaining - 1)];
};
console.log(countdown(3)); // [3, 2, 1, "done"]
- Self-reference safety: Inside
step, callingstep(...)continues to work even if an outer variable reference changes. - Explicit names aid debugging: Named functions provide clearer names in stack traces and profiler output than unnamed functions.
3. Conditional / Block Scoping and Choosing Between Them
In strict mode (and ES modules), function declarations inside { ... } blocks are scoped to that block rather than leaking out like legacy var, whereas function expressions follow the exact scoping rules of const, let, or var and work naturally as callbacks, arguments, or IIFEs:
// Function expressions pass directly as arguments or non-mutating callbacks
function normalizeTags(rawTags) {
if (!Array.isArray(rawTags)) {
throw new TypeError("Expected rawTags to be an array.");
}
const formatTag = function (entry) {
return String(entry).trim().toLowerCase();
};
return rawTags
.filter((item) => typeof item === "string" && item.trim().length > 0)
.map(formatTag);
}
console.log(normalizeTags([" React ", "", " TypeScript "]));
// ["react", "typescript"]
- Use function declarations for standalone, top-level or module-level named functions where hoisting or clear named declarations fit best.
- Use
constfunction expressions (or arrow functions) for inline callbacks, conditional/dynamic assignment, and non-reassigned function values.
