Dart by Example: Lexical Scope
Dart is a lexically scoped language.Loops that declare their variable will have a new version of that variable for each iteration.
1. main() {
2. var functions = [];
4. for (var i = 0; i < 3; i++) {
5. functions.add(() => i);
6. }
8. functions.forEach((fn) => print(fn()));
10. }
1. $ dart lexical_scope.dart
2. 0
3. 1
4. 2
Compared to javascript:
1. var functions = [];
3. for (var i = 0; i < 3; i++) {
4. functions[i] = function() { return i };
5. }
7. functions.forEach(function (fn) { console.log(fn())});
1. $ node lexical_scope.js
2. 3
3. 3
4. 3
