What is the difference between a function declaration and function expression?
Two ways to define a function, differing mainly in hoisting.
Declaration — function foo(){}: fully hoisted, so you can call it before it's defined.
Expression — const foo = function(){}: only the variable is hoisted, so calling early fails.
Use declarations for top-level functions; expressions for conditional or assigned functions.
// Declaration — hoisted completely
sayHello(); // Works! (hoisted)
function sayHello() {
console.log('Hello!');
}
// Expression — NOT hoisted (follows var/let/const rules)
// greet(); // TypeError: greet is not a function
var greet = function() {
console.log('Hi!');
};
// greet is hoisted as undefined, calling undefined() throws TypeError
// let/const expression — TDZ
// wave(); // ReferenceError (temporal dead zone)
const wave = () => console.log('Wave!');
// Named function expression (useful for recursion and stack traces)
const factorial = function fact(n) {
return n <= 1 ? 1 : n * fact(n - 1); // 'fact' accessible inside only
};Function declarations are fully hoisted (callable anywhere). var expressions hoist as undefined (calling throws TypeError, not ReferenceError). let/const expressions are in TDZ (ReferenceError). Named function expressions have the name accessible only inside the function (useful for recursion).
Declarations = fully hoisted (callable before definition). Expressions = follow variable rules (var=undefined TypeError, let/const=TDZ ReferenceError).
This hoisting difference is the most tested detail. Named function expressions for recursion and better stack traces.