JavaScriptAdvanced JavaScript Concepts
JavaScript Hoisting
Understand JavaScript hoisting, how variables and functions are moved to the top of their scope during execution, and common pitfalls developers face.
What is Hoisting in JavaScript?Link to this section
Hoisting is JavaScript’s behavior of moving declarations to the top of their scope during the compilation phase, before the code is executed.
This means JavaScript is aware of variables and functions before they are actually written in the code, though their values may not be available yet.
Why Hoisting ExistsLink to this section
JavaScript executes code in two phases:
- Memory creation phase
- Execution phase
Hoisting with var:Variables declared with var are hoisted and initialized with undefined.
Explanation:
The declaration var a is hoisted, but the assignment happens later. So JavaScript knows a exists, but its value is undefined at the time of logging.
Hoisting with let and const:Variables declared with let and const are hoisted, but not initialized.
Explanation:
Accessing b before its declaration causes a runtime error because it exists in the Temporal Dead Zone (TDZ).
Temporal Dead Zone (TDZ)Link to this section
The Temporal Dead Zone is the time between:
- When a variable is hoisted
- When it is initialized
note
TDZ helps catch bugs early and enforces safer coding practices.
Function HoistingLink to this section
Function declarations are fully hoisted, including their function body.
Explanation:
The function can be called before its declaration because JavaScript hoists the entire function.
Function Expressions and HoistingLink to this section
Function expressions follow variable hoisting rules.
Explanation:
This causes an error because sayHi is not initialized at the time of execution.
Common Hoisting MistakesLink to this section
- Using variables before declaration
- Mixing var with let/const
- Assuming function expressions are hoisted like functions
warning
Hoisting-related bugs are common in interviews and production issues.
Best Practices to Avoid Hoisting IssuesLink to this section
- Always declare variables at the top of their scope
- Prefer let and const
- Avoid relying on hoisting behavior
- Write readable, predictable code
tip
If your code works only because of hoisting, it’s probably not good code.
Check Your Understanding
Question 1 of 4What is hoisted in JavaScript?
Select all that apply
Practice Challenges
- Write a program using var before declaration and predict the output.
- Convert a hoisting-related error into correct code using let or const.
- Call a function before and after its declaration to observe behavior.
- Write a snippet that demonstrates the Temporal Dead Zone.