Table of contents
What is Scope?
Scope is like the area where a variable "lives" and can be used.
In Dart, it is like a territory where Dart knows about a variable.
Lexical scoping means Dart figures out the territory based on where you write your code. So, if you define a variable inside a function or a block of code, Dart says," Okay, this variable belongs to this function or block. It's only accessible from inside here."
There are mainly two types of scopes in Dart:
Global Scope: Variable declared outside any function or class have global scope. They can be accessed from anywhere in the Dart file.
Local Scope: Variables declared inside a function or block of code have local scope. They are only accessible within the function or block where they are defined.
// Global scope variable
var globalVariable = "I'm in global scope";
void myFunction() {
// Local scope variable
var localVariable = "I'm in local scope";
print(globalVariable); // Accessible
print(localVariable); // Accessible
}
void main() {
print(globalVariable); // Accessible
// print(localVariable); // Not accessible - causes an error
}
What is Closure:
Imagine you have a little function, and inside that function, you have some variables. Now, normally, when the function finishes running, those variables disappear. They're like thoughts that pop into your head and they vanish.
But with the closure, it is like having a little pocket where you can keep those variables safe even after the function is done. So, even when the function is finished, if you have a closure, it remembers those variables and can still use them letter.
Lexical Closures
Function makeAdder(int addBy) {
return (int i) => addBy + i; // This is a closure
}
void main() {
var add3 = makeAdder(3); // Closure capturing addBy = 3
var add5 = makeAdder(5); // Closure capturing addBy = 5
print(add3(2)); // Output: 5 (3 + 2)
print(add5(2)); // Output: 7 (5 + 2)
}
In the above example, makeAdder
returns a closure that captures the addBy
parameter. Even after makeAdder
has finished executing, the returned closure still has access to the addBy
variable. This allows us to create functions (add3
and add5
) that increment their arguments by a specific amount.