1. Function Declaration
- A function declaration defines a named function using the
functionkeyword. - It is hoisted completely, meaning you can call the function before it is defined in the code.
✅ Example:
sayHello(); // ✅ Works due to hoisting
function sayHello() {
console.log("Hello from declaration!");
}
2. Function Expression
- A function expression assigns a function (anonymous or named) to a variable.
- Only the variable declaration is hoisted, not the function definition.
- That means you cannot call it before defining it.
✅ Example:
sayHi(); // ❌ Error: Cannot access 'sayHi' before initialization
const sayHi = function () {
console.log("Hello from expression!");
};
3. Key Differences
| Feature | Function Declaration | Function Expression |
|---|---|---|
| Hoisting | Fully hoisted (can be called before definition) | Only variable is hoisted (function not available before definition) |
| Syntax | function name() {} | const name = function() {} |
| Use case | When you want functions available throughout scope | When you want functions conditionally, inline, or assigned |
| Anonymous functions | Not possible (always needs a name) | Possible (can be anonymous or named) |
👉 In short:
- Declarations → Hoisted, global availability.
- Expressions → Not hoisted (only the variable is), often used in callbacks or assigned to variables.
