All topics
Functionsbeginner

Function Hoisting and Declaration vs Expression

How function declarations, function expressions, and named function expressions differ in hoisting behavior and use cases.

JavaScript offers several ways to define a function, and the differences between them go beyond stylistic preference — they affect hoisting, naming for stack traces, and whether the function can be called before its definition appears in the source. This is a frequent early interview question because it combines hoisting knowledge with basic syntax literacy.

A function declaration is like a fully-built house that's already standing when you arrive, ready to walk into. A function expression is like an empty lot with a sign showing whose house will eventually be built there — the sign (variable name) exists early, but you can't move in (call it) until construction (the assignment) actually finishes.

Key Concepts

1
A function declaration (function greet() {}) is fully hoisted: both its name and its implementation are available throughout the entire enclosing scope from the very top, which is why you can call greet() on a line before its declaration appears later in the file. A function expression (const greet = function () {}) is not hoisted the same way — only the variable declaration (greet) is hoisted according to whatever keyword is used (var, let, or const), while the function assignment itself only happens when execution reaches that line, so calling it earlier throws (a TypeError for var, since greet would be undefined, or a ReferenceError for let/const, due to the temporal dead zone).
function greet() {}greet()const greet = function () {}greetvar
2
A named function expression (const greet = function sayHi() {}) gives the function an internal name (sayHi) that's usable for recursion inside the function body and shows up more helpfully in stack traces during debugging, while still being invoked externally via the variable name (greet), not the internal name, which is not accessible outside the function itself.
const greet = function sayHi() {}sayHigreet
3
The practical guidance many style guides converge on: function declarations are fine and readable for top-level utility functions, but function expressions (especially arrow functions assigned to const) are often preferred for callbacks, object methods, and anywhere you want the 'define before use' discipline that comes naturally from disallowing early calls.
const