Hoisting & Closures
Master advanced JavaScript concepts! Learn hoisting, closures, and how JavaScript executes code.
Master advanced JavaScript concepts! Learn hoisting, closures, and how JavaScript executes code. This hands-on tutorial focuses on practical implementation of hoisting & closures concepts.
Hoisting & Closures
These are two of the most asked-about concepts in JavaScript interviews. Understanding them proves you know how JS works under the hood.
1. Hoisting π
What is it? JavaScript's behavior of moving declarations to the top of their scope before code execution.
How it works:
- Function Declarations are fully hoisted (you can call them before defining them).
varis hoisted but initialized asundefined.letandconstare hoisted but stay in a "Temporal Dead Zone" (TDZ) until the line of code is reached.
2. Closures π
What is it? A closure is a function that "remembers" the variables from the place where it was defined, even after that place (scope) has finished executing.
Why use it?
- Data Privacy: To create private variables that can't be accessed from outside.
- Function Factories: To create functions with preset configurations.
How it works: Inner functions keep a reference to the outer function's variables.
3. Practical Example: Private Variables π‘οΈ
In many languages, you have private variables. In JavaScript, we use closures to achieve this.
4. Common Pitfall: Loops & Closures π
A classic interview question!
AI Mentor
Confused about "JavaScript hoisting, closures, lexical scope, and private variables"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 4What happens if you call a function declaration before it is defined?
Key Takeaways
β
Hoisting moves declarations to the top.
β
let/const are safer than var (no accidental hoisting bugs).
β
Closures allow functions to "remember" data.
β
Use closures for Data Privacy and Encapsulation.
What's Next?
You've mastered the hard parts! Now let's relax with some modern syntax sugar in ES6+ Features.
Keep coding! π