JavaScript Deep Dive 2026: Closures, Promises & Event Loop

JavaScript Deep Dive

नमस्ते दोस्तों! 👋

Swagat hai The Easy Master par! 🚀

Agar aap JavaScript seekh rahe ho aur React, Node.js ya Next.js mein jaana chahte ho, toh ye 6 topics aapke liye must-master hain: var/let/const, Closures, Prototype Chain, Event Loop, Promises aur async/await.

Bahut se students inme confuse ho jaate hain. Is guide mein hum zero se hero level tak har cheez ko simple examples, real output, CodePen live demos aur diagrams ke saath samjhayenge.

Chaliye shuru karte hain!

1. var, let aur const (JavaScript Deep Dive ka Base)

Doston, ye teen keywords samajhna JavaScript ka base hai.

Quick Comparison Table:

KeywordScopeHoistingRe-assignRe-declareTemporal Dead Zone
varFunction ScopeYesYesYesNo
letBlock ScopeYesYesNoYes
constBlock ScopeYesNoNoYes

Example – Hoisting

console.log(a); // undefined
var a = 10;

console.log(b); // ReferenceError
let b = 20;

Example – Block Scope (Sabse Important)

JavaScript

if (true) {
  var x = 5;     // Poora function mein visible
  let y = 10;    // Sirf is block mein
  const z = 15;  // Sirf is block mein
}

console.log(x); // 5
// console.log(y); // Error

Pro Tip: Hamesha let aur const use karo. var sirf purane legacy code mein dekho.


2. Closures in JavaScript Deep Dive

Closures JavaScript deep dive ka sabse powerful aur interview mein sabse zyada pucha jaane wala topic hai.

Closure kya hai? Jab ek inner function apne outer function ke variables ko “yaad” rakhta hai, bhale hi outer function execute ho chuka ho – usko Closure kehte hain.

Real Example – Private Counter

function createCounter() {
  let count = 0;   // Private variable

  return function() {
    count++;
    console.log("Count:", count);
  };
}

const counter1 = createCounter();
counter1(); // Count: 1
counter1(); // Count: 2

const counter2 = createCounter(); // Naya counter
counter2(); // Count: 1

Live Demo on CodePen: Closure Counter Demo

Common Interview Question (Loop + setTimeout):

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1000);
} 
// Output: 3 3 3

for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1000);
} 
// Output: 0 1 2

Use Cases: Private variables, React hooks, data hiding.


3. Prototype Chain – JavaScript ka Inheritance

JavaScript mein classes nahi, prototypes se inheritance hota hai.

Simple Example

function Person(name) {
  this.name = name;
}

Person.prototype.greet = function() {
  console.log("Hello, I am " + this.name);
};

const shrikant = new Person("Shrikant");
shrikant.greet();

Prototype Chain Visual:

JavaScript prototype chain diagram

    Modern ES6 Class Way

    class Student {
      constructor(name) { this.name = name; }
      study() { console.log(this.name + " is studying"); }
    }

    4. Event Loop – JS Asynchronous Magic

    JavaScript single-threaded hai, lekin async code smoothly chalta hai – iska credit Event Loop ko jaata hai.

    Main Parts:

    • Call Stack (Synchronous code)
    • Web APIs (setTimeout, fetch, DOM)
    • Callback Queue & Microtask Queue
    • Event Loop

    Example Code

    console.log("Start");
    
    setTimeout(() => console.log("Timeout"), 0);
    
    Promise.resolve().then(() => console.log("Promise"));
    
    console.log("End");
    
    // Output:
    // Start
    // End
    // Promise
    // Timeout
                    ┌─────────────────────┐
                    │     CALL STACK      │
                    │ (Sync Code Runs)    │
                    └─────────┬───────────┘
                              │
                              ▼
                    ┌─────────────────────┐
                    │      WEB APIs       │
                    │ (setTimeout, fetch, │
                    │  DOM events, etc.)  │
                    └───────┬───────┬─────┘
                            │       │
             ┌──────────────┘       └──────────────┐
             ▼                                     ▼
    ┌─────────────────────┐           ┌─────────────────────┐
    │  CALLBACK QUEUE     │           │  MICROTASK QUEUE    │
    │ (setTimeout, etc.)  │           │ (Promises, then)    │
    └─────────┬───────────┘           └─────────┬───────────┘
              │                                 │
              └──────────────┬──────────────────┘
                             ▼
                    ┌─────────────────────┐
                    │     EVENT LOOP      │
                    │ (Check Stack First)│
                    └─────────┬───────────┘
                              │
                              ▼
                    ┌─────────────────────┐
                    │     CALL STACK      │
                    │ (Execute Tasks)     │
                    └─────────────────────┘

    Pro Tip: Microtasks (Promise.then) Macrotasks (setTimeout) se pehle execute hote hain.


    5. Promises – Future Values Handle Karna

    Promise teen states mein hota hai: Pending → Fulfilled → Rejected

    Basic Promise

    const fetchData = new Promise((resolve, reject) => {
      setTimeout(() => resolve("Data aa gaya!"), 2000);
    });
    
    fetchData.then(result => console.log(result));

    6. async/await – Sabse Clean Way (2026 Favorite)

    async/await Promises ka sugar syntax hai – code synchronous jaisa dikhta hai.

    async function getUser() {
      try {
        const res = await fetch("https://theeasymaster.com/api");
        const data = await res.json();
        console.log(data);
      } catch (err) {
        console.log("Error:", err);
      }
    }
    
    getUser();

    7. Sab Topics Ek Saath – Practical Example

    JavaScript

    function createCounter() { ... } // Closure
    
    async function main() {
      console.log("Start");
      const data = await new Promise(resolve => setTimeout(() => resolve("Done"), 1000));
      console.log(data);
      createCounter()();
    }
    
    main();

    Common Mistakes & Pro Tips

    • var use karne se hoisting bugs
    • Closure mein loop variable galat capture
    • Promise reject ko catch na karna
    • async function ke andar await bhool jaana

    Pro Tip: Hamesha try…catch async/await ke saath use karo.


    Conclusion

    Doston, aaj aapne JavaScript ke sabse powerful aur confusing topics deeply samajh liye – Closures, Promises, async/await, Event Loop, Prototype Chain aur var/let/const.

    Ab aap confident ho kar interviews de sakte ho aur real projects bana sakte ho.

    Action Step: Aaj hi ek chhota project banao – Private Counter using Closure + async data fetch with async/await. CodePen pe upload karke link comment mein daal do!

    Agar koi doubt ho ya kisi topic ka extra example chahiye, toh comment zaroor karna. Main help karunga.

    Happy Coding!

    Additional Resources

    For those interested in expanding their skills with APIs, check out our Top 10 Free APIs for Practice in 2025 and improve your JavaScript mastery with our Master ES6 JavaScript – Complete Guide at Master ES6 JavaScript – Complete Guide.