Lexical Scoping vs Closures

Lexical Scoping vs Closures

ยท

2 min read

Lexical scoping and closures are related concepts in programming, but they are not the same thing. Here's a brief explanation of each:

  1. Lexical scoping: refers to the way a programming language determines how variables are scoped (i.e., how they are accessible or not) based on their position in the code. In a lexically-scoped language like JavaScript, a variable declared inside a function is only accessible within that function and any nested functions within it. The outer scope, such as the global scope, cannot access those variables.

     function outer() {
       let x = 10;
       function inner() {
         console.log(x);
       }
       inner();
     }
     outer(); // Output: 10
    

    In this example, we have a function outer that declares a variable x and a nested function inner that logs the value of x to the console. When we call outer, it calls inner, which is able to access the variable x because of lexical scoping. Since x is declared in the outer function, it is accessible to the inner function and can be logged into the console.

  2. Closures: A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure "closes over" the variables it needs from its outer scope and maintains a reference to them, even if those variables would otherwise be inaccessible. This can be useful for creating private variables or for preserving state across function calls.

     function outer() {
       let x = 10;
       function inner() {
         console.log(x);
       }
       return inner;
     }
     let closureFunc = outer();
     closureFunc(); // Output: 10
    

    In this example, we have the same outer and inner functions as before, but this time we're returning the inner function from outer and assigning it to a variable closureFunc. When we call closureFunc, it logs the value of x to the console, just like before. However, the difference here is that inner has access to the variable x even after outer has finished executing, Thanks to the concept of closures. In other words, inner "closes over" the variable x and maintains a reference to it, even though outer has finished executing.

Closures are possible in languages with lexical scoping, but not all languages with lexical scoping have closures. In JavaScript, for example, closures are commonly used to create private variables and functions, and to preserve state in asynchronous code.

Did you find this article valuable?

Support Sourav Bandyopadhyay by becoming a sponsor. Any amount is appreciated!

ย