JavaScript Scope and Closures
Lexical Scope example
function outer() { const x = 10; function inner() { console.log(x); // Accesses variable x from outer function } inner(); } outer();
Closures example
function outer() { const x = 10; function inner() { console.log(x); // Accesses variable x from outer function (closure) } return inner; } const closureFunc = outer(); closureFunc(); // Prints 10
Closure Scope Chain
is the series of linked scopes that a function has access to, including its own scope and the scopes of its outer functions. This chain allows closures to access variables from their lexical environment. Example: In the code above, the closure function inner has access to the scope of outer even after outer has finished executing.
Closures
occur when a function retains access to variables from its lexical scope even after the outer function has finished executing. They allow for the preservation of state between function calls.
Scope
refers to the accessibility and visibility of variables in different parts of a JavaScript program. It determines where variables and functions are available for use. Examples: Global scope, local scope, function scope, block scope.
Use Cases for Closures
Closures are commonly used for encapsulation, data privacy, and maintaining state across function calls. They are particularly useful when dealing with asynchronous code or creating factory functions. Example: Creating private variables, implementing memoization, handling event listeners, and timeouts.
Garbage Collection and Closures
Closures can sometimes lead to memory leaks if not used properly. When closures capture references to variables, those variables may continue to be held in memory even if they are no longer needed. Example: If a closure retains references to large objects or functions that are no longer needed, it can prevent those objects or functions from being garbage collected, leading to memory leaks.
Lexical Scope
also known as static scope, is a concept where the visibility of variables is determined by their location in the source code during the lexical analysis phase. Inner functions have access to variables defined in outer functions.
