Open In App

What is Lexical scope and lexical closures in Dart

Lexical Scope:

It is the term used in various programming languages (not just in dart), to describe a condition where the scope of the variable is not present when the control is out of the block of code where the scope was present. Dart is a lexically scoped language, i.e. you can find the scope of the variable by the help of the braces.

Example 1: Lexical Scope of a variable.






// Declaring a variable whose scope is global
var outter_most;
  
void main() {
// This variable is inside main and can be accessed within
  var inside_main;
  
  void geeksforgeeks() {
// This variable is inside geeksforgeeks and can be accessed within
    var inside_geeksforgeeks;
  
    void geek() {
// This variable is geek and can be accessed within
      var inside_geek;
  
    }
  }
}

The above code depicts, about the scope of the variable in dart function and how their scope 
ends outside braces.

Lexical Closures:

In programming languages, a lexical closure, also called closure or function closure, is a way of implementing lexical scope name binding in a function. It is a function object that has access to variables in its lexical scope, even when the function is used outside the scope.

Example 2:






Function geeksforgeeks(num add) {
  return (num i) => add + i;
}
  
void main() {
  // Create a function that adds 2.
  var geek1 = geeksforgeeks(2);
  
  // Create a function that adds 4.
  var geek2 = geeksforgeeks(4);
  
  print(geek1(3));
  print(geek2(3));
}

Output:

5
7
Note:
Functions can close over variables defined in surrounding scopes. In the following example,
geeksforgeeks() captures the variable addBy. Wherever the returned function goes, it remembers
"add" variable.

Article Tags :