Function Declaration vs Function Expression in JavaScript: Key Differences
function declaration defines a named function that is hoisted and available before its definition in code, while a function expression assigns a function to a variable and is not hoisted in the same way, so it can only be used after its definition. Function declarations are useful for defining reusable functions upfront, whereas function expressions offer more flexibility, such as creating anonymous functions or closures.Quick Comparison
Here is a quick side-by-side comparison of function declarations and function expressions in JavaScript.
| Aspect | Function Declaration | Function Expression |
|---|---|---|
| Syntax | Starts with the function keyword followed by a name | Function assigned to a variable, can be anonymous or named |
| Hoisting | Fully hoisted, callable before definition | Variable is hoisted but assignment is not; callable only after assignment |
| Name | Must have a name | Can be anonymous or named |
| Use case | Defines reusable functions upfront | Used for callbacks, closures, or conditional definitions |
| Creation time | Created at parse time | Created at runtime when assignment runs |
| Scope | Function name is scoped to enclosing scope | Variable holding function follows variable scope |
Key Differences
Function declarations are hoisted completely, meaning JavaScript loads them before running any code. This allows you to call the function anywhere in the scope, even before the line where it is written. They always have a name and are easy to spot in code.
On the other hand, function expressions are not hoisted in the same way. The variable declaration is hoisted but not the assignment, so the function is created only when the assignment line runs. This means you cannot call them before they appear in the code. They can be anonymous (no name) or named, which is useful for callbacks or passing functions as values.
Function expressions provide more flexibility, such as creating closures or immediately invoked function expressions (IIFE). Function declarations are simpler and better for defining main functions that you want available throughout your code.
Code Comparison
Here is how you define and use a function declaration to add two numbers.
function add(a, b) { return a + b; } console.log(add(2, 3));
Function Expression Equivalent
Here is the equivalent function using a function expression assigned to a variable.
const add = function(a, b) { return a + b; }; console.log(add(2, 3));
When to Use Which
Choose function declarations when you want clear, hoisted functions that are available anywhere in their scope. They are great for main functions that you call multiple times.
Choose function expressions when you need more control, such as creating anonymous functions, closures, or passing functions as arguments. They are also useful when you want to define functions conditionally or inside other functions.