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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
  
    }
  }
}

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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));
}

chevron_right


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.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.