Advanced
Hoisting
Declarations are moved to the top of their scope before execution.
1. Explanation
JavaScript hoists var declarations (initialised to undefined) and function declarations (fully) to the top of their scope. let and const are hoisted but not initialised — accessing them before the declaration throws a ReferenceError (the Temporal Dead Zone).
2. Example
Try it yourself
Console
Click Run to see output.
3. Expected output
output
undefined
hi4. Common mistakes
- ✗Relying on var hoisting for cleaner-looking code — it's confusing, prefer let/const
- ✗Calling a function expression before it's defined
- ✗Forgetting that class declarations are also in the TDZ
5. Practice questions
- Log a let variable before it's declared and observe the error
- Define a function expression and try calling it before
- Explain in comments why a particular snippet logs undefined