Lexical closures

A closure is a function object that has access to variables in itslexical scope, even when the function is used outside of its originalscope.

Functions can close over variables defined in surrounding scopes. In thefollowing example, makeAdder() captures the variable addBy. Wherever thereturned function goes, it remembers addBy.

  1. /// Returns a function that adds [addBy] to the
  2. /// function's argument.
  3. Function makeAdder(num addBy) {
  4. return (num i) => addBy + i;
  5. }
  6. void main() {
  7. // Create a function that adds 2.
  8. var add2 = makeAdder(2);
  9. // Create a function that adds 4.
  10. var add4 = makeAdder(4);
  11. assert(add2(3) == 5);
  12. assert(add4(3) == 7);
  13. }