JavaScript Closure Definition and Use Cases

Interview Question: What is a Closure in JavaScript? - A closure is created when a function remembers and accesses variables from its outer (lexical) scope, even after the outer function has finished executing. In simple words: A function + its outer scope = Closure ● Example of Closure : function outer() { let count = 0; function inner() { count++; console.log(count); } return inner; } const fn = outer(); fn(); // 1 fn(); // 2 -> inner() remembers count even after outer() is done. ● Why Closures are Useful? - Data hiding / encapsulation - Maintaining state - Callback functions - Event handlers • Interview Tip: Closures are possible because JavaScript uses lexical scoping, not dynamic scoping. #JavaScript #InterviewPrep #Closures #WebDevelopment #Frontend #MERN #LearnInPublic #CodingJourney #Backend #30DaysOfJavaScript #Backend #BDRM #BackendDevWithRahulMaheshwari

  • graphical user interface, website

To view or add a comment, sign in

Explore content categories