A **function expression** creates a function and assigns it to a variable. They are **not hoisted** — you cannot call them before the line where they are defined. Named function expressions give the function a name only accessible inside its own body (useful for recursion and stack traces).
1Understanding Function Expressions
A function expression creates a function and assigns it to a variable. They are not hoisted — you cannot call them before the line where they are defined. Named function expressions give the function a name only accessible inside its own body (useful for recursion and stack traces).
Use function expressions when you need to conditionally create a function or pass it as an argument.
// Function expression - NOT hoisted
// console.log(multiply(2, 3)); // ReferenceError!
const multiply = function(a, b) {
return a * b;
};
console.log(multiply(2, 3)); // 62Practical Example
Here is a real-world application of Function Expressions showing how it is used in production JavaScript code.
// Named function expression (name only inside)
const factorial = function fact(n) {
return n <= 1 ? 1 : n * fact(n - 1); // fact available here
};
console.log(factorial(5)); // 120
// console.log(fact(5)); // ReferenceError - not outside3Best Practices
Follow these guidelines when working with Function Expressions:
1. Use const to declare function expressions
2. Name your function expressions for better stack traces
3. Function expressions passed as callbacks are common in JavaScript
Tip: Use function expressions when you need to conditionally create a function or pass it as an argument.
// Function expression - NOT hoisted
// console.log(multiply(2, 3)); // ReferenceError!
const multiply = function(a, b) {
return a * b;
};
console.log(multiply(2, 3)); // 6