Closure in javascript
Closures in JavaScript Closures are one of the most important concepts in JavaScript. They can look confusing at first because they involve functions, lexical scope, and lexical environments together. But once we understand how these concepts are connected, closures become much easier to understand. A simple definition of closure is: A closure is a function that remembers and can access variables from its surrounding lexical environment even after the outer function has finished executing. The word "remembers" here doesn't mean that JavaScript literally copies the variables into the function. Instead, the function maintains a connection to the lexical environment in which it was created. Let's understand it with an example Consider the following code: function outer () { let name = " Abimanyu " function inner () { console . log ( name ) } return inner } let myFunction = outer () myFunction () When outer() is called, JavaScript creates a lexical environment for it. That environment contains the variable name : Outer Lexical Environment name → "Abimanyu" The inner() function is created inside outer() , so it has access to that surrounding environment. When outer() returns inner , the function is stored in myFunction . Now outer() has finished executing, but myFunction still refers to inner() . myFunction ↓ inner() ↓ Outer Lexical Environment ↓ name → "Abimanyu" When we call: myFunction () inner() needs the value of name . Since name is not inside its own environment, JavaScript looks through its surrounding environment and finds name in the environment created by outer() . This is the important part of a closure: the function retains access to the environment where it was created, even though the outer function has already finished executing. Why doesn't name disappear? This is where closures are often misunderstood. You might think that once outer() finishes, everything created inside it should disappear. But inner() still has a reference to the environment containin