JavaScript Closures: Data Privacy & Functional Programming

Day 9/50 – JavaScript Interview Question? Question: What is a closure and why is it useful? Simple Answer: A closure is a function that retains access to variables from its outer (enclosing) scope, even after the outer function has finished executing. 🧠 Why it matters in real projects: Closures enable data privacy (creating private variables), factory functions, memoization, and functional programming patterns. They're fundamental to modern JavaScript frameworks and libraries like React (hooks rely heavily on closures). 💡 One common mistake: Expecting closures to capture the value of a variable at the time of creation. Closures capture variables by reference, not by value, which can cause issues in loops with var. 📌 Bonus: // Classic closure problem with var for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); } // Prints: 3, 3, 3 // Fixed with let (block scope) for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); } // Prints: 0, 1, 2 // Practical use - private variables function createCounter() { let count = 0; // Private! return { increment: () => ++count, getCount: () => count }; } #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews

To view or add a comment, sign in

Explore content categories