a - closure intro closure is a function that retains access to its lexical scope, even when the function is executed outside of that scope. This means that a closure can "remember" and access variables from the environment in which it was created... even after that environment has finished executing. Key Concepts: 1. Lexical Scope: Lexical scope refers to the way variables are scoped according to their location in the code, rather than when they are called. A function's lexical environment is determined by where it was defined, not where it was executed. 2. Execution Context: The execution context is the environment in which JavaScript code executes. It includes the variable and function declarations that are currently accessible. 3. Closure Creation: *When a function is created inside another function, the inner function retains access to the variables of the outer function's scope. Common Misconceptions: Closures Capture Values, Not References → When a closure captures a variable, it captures the value of that variable at the time the closure was created. Changes to the original variable after the closure is created do not affect the closure. In conclusion they enable encapsulation, data hiding, and state management, making them an essential tool for any JavaScript developer.
b - closure examples 1. Function Definition → createCounter is defined with a local variable count initialized to 0. Inside createCounter, another function (an anonymous function) is defined and returned. 2. Closure Creation → When createCounter is called, it returns the inner function. This inner function retains access to the count variable from its lexical scope (createCounter). 3. Usage of Closure: The returned inner function (closure) is stored in the counter variable. Each time counter() is called, it increments and logs the count variable. Use Cases for Closures: Encapsulation and Data Hiding → You can use closures to create private variables that cannot be accessed from outside the function. Factory Functions: Closures are often used to create factory functions, which generate objects with specific behavior. Maintaining State Across Asynchronous Operations: Closures can help maintain state in asynchronous operations by retaining access to variables.