What is Lexical scope and lexical closures in Dart
Last Updated :
08 Jun, 2020
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.
var outter_most;
void main() {
var inside_main;
void geeksforgeeks() {
var inside_geeksforgeeks;
void geek() {
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() {
var geek1 = geeksforgeeks( 2 );
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.
Share your thoughts in the comments
Please Login to comment...