JavaScript

Hoisting & Closures

Master advanced JavaScript concepts! Learn hoisting, closures, and how JavaScript executes code.

By TechCoder TeamLast updated: 2026-06-02
In a Nutshell

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).
  • var is hoisted but initialized as undefined.
  • let and const are hoisted but stay in a "Temporal Dead Zone" (TDZ) until the line of code is reached.
JAVASCRIPT PLAYGROUND
⏳ Loading editor…

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.

JAVASCRIPT PLAYGROUND
⏳ Loading editor…

3. Practical Example: Private Variables πŸ›‘οΈ

In many languages, you have private variables. In JavaScript, we use closures to achieve this.

JAVASCRIPT PLAYGROUND
⏳ Loading editor…

4. Common Pitfall: Loops & Closures πŸ”„

A classic interview question!

JAVASCRIPT PLAYGROUND
⏳ Loading editor…

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 4

What happens if you call a function declaration before it is defined?

Error
It works (Hoisting)
It returns undefined
It crashes the browser

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! πŸš€