π What is Closure in JavaScript? ? Explained with Simple Examples

In JavaScript, a closure is created when a function "remembers" the variables from its outer scope even after the outer function has finished executing . This concept allows functions to access variables from an enclosing scope or function — even after that outer function has returned. Closures are a powerful feature in JavaScript that enable data encapsulation, callback handling, and the creation of private variables. π‘ Let's Understand with an Example function outerFunction() { let outerVariable = "I am from outer scope!"; function innerFunction() { console.log(outerVariable); // Accessing variable from outer scope } return innerFunction; } const closureFunc = outerFunction(); closureFunc(); // Output: I am from outer scope! π Explanation: outerFunction defines a variable outerVariable . innerFunction is declared inside outerFunction and uses that variable. Even after outerFunction() has finished executing, innerFunc...
Comments
Post a Comment