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 = [];
  3. for (var i = 0; i < 3; i++) {
  4. functions.add(() => i);
  5. }
  6. functions.forEach((fn) => print(fn()));
  7. }
  8.  
  1. $ dart lexical_scope.dart
  2. 0
  3. 1
  4. 2

Compared to javascript:

  1. var functions = [];
  2. for (var i = 0; i < 3; i++) {
  3. functions[i] = function() { return i };
  4. }
  5. functions.forEach(function (fn) { console.log(fn())});
  1. $ node lexical_scope.js
  2. 3
  3. 3
  4. 3

by @jryanio | source | license