Lexical Scoping vs Closures

Total
0
Shares

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

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
Enter fullscreen mode

Exit fullscreen mode

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.

Closures: A closure is a function that has access to variables in its lexical scope, even after that scope has exited. 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
Enter fullscreen mode

Exit fullscreen mode

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.

Total
0
Shares

Boost Your Next Project with My Comprehensive List of Free APIs – 1000+ and Counting!

If you’re a developer or programmer, you know that APIs can be incredibly helpful when it comes to…

You May Also Like