Understanding the difference between declarations and expressions is fundamental in JavaScript. Both are ways to define functions or variables, but they behave differently.

💡 What is a Declaration?
A declaration explicitly defines a function or variable and is hoisted, meaning it is available anywhere in its scope before its actual place in the code.
💡 What is an Expression?
An expression produces a value and can be assigned to a variable. Function expressions are not hoisted and only available after the assignment.
| Feature | Declaration | Expression |
|---|---|---|
| Syntax | function foo() {} | const foo = function() {} |
| Hoisting | Hoisted (usable before declaration) | Not hoisted (usable after assignment) |
| Named/Anonymous | Always named | Can be anonymous or named |
| Use case | Standard function definition | Assign functions dynamically or inline |
| Feature | Declaration | Expression |
|---|---|---|
| Example | let x; | let x = 5 + 3; |
| Purpose | Creates a variable | Computes a value to assign |
| Execution | Variable is declared | Expression is evaluated to produce a value |
📌 Deep Dive: Function Declaration vs Expression Hoisting
// Function Declaration (hoisted)
sayHello();
function sayHello() {
console.log("Hello from declaration!");
}
// Function Expression (not hoisted)
try {
sayHi();
} catch (e) {
console.log(e.message); // sayHi is not a function
}
const sayHi = function() {
console.log("Hello from expression!");
};
sayHi();
sayHi is not a function
Hello from expression!
⚠️ Important
Function declarations are hoisted completely, but function expressions behave like normal variables and are not initialized until assigned.
💡 Summary
- Declarations define functions or variables upfront and are hoisted.
- Expressions produce values and are evaluated when the code runs.
- Use declarations when you want hoisting and clear function definitions.
- Use expressions for more flexible or conditional function assignments.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which of the following is true about function declarations?
Question 2 of 2
What happens if you try to call a function expression before it is assigned?
Loading results...