Send Close Add comments: (status displays here)
Got it!  This site uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.nbsp; Note: This appears on each machine/browser from which this site is accessed.
Iterators and generators


1. Iterators and generators

2. Iterators and generators
Suppose one wants to create a piece of code that will return the even numbers in sequence as requested.

One could program this with classes.

But one can also program this with functions in languages that support functions as first class objects.

Here are some examples.

3. Lua code
Here is the Lua code.

Here is the output of the Lua code.


4. Lua output
Here is the output of the Lua code.

5. Closures
Those local variables in the function nextEvenMake1 do not disappear.

The collection of these variables are what are called closure variables and hidden from access except through the function that is returned.

6. Lambda closures
If the returned function has no explicit name (and sometimes even when it has an explicit name) the resulting closure is often called a lambda closure, from the Greek letter "λ" (lambda).

The study of simple and pure functional languages is sometimes called the lambda calculus, or Λ-calculus.

7. JavaScript code
Here is the JavaScript code.

Here is the output of the JavaScript code.


8. JavaScript output
Here is the output of the JavaScript code.

9. Strict mode
JavaScript has good parts and bad parts.

The bad parts cannot be changed as too much code (and Internet web pages) rely on that behavior.

However, in JavaScript an expression can be used as a statement, even if it has no effect.

10. Expression statement
The following JavaScript expression used as a statement has no computational effect.
"use strict";

All older JavaScript systems that accept bad parts of the language process this statement that has no effect.

So do newer JavaScript systems. But the text "use strict" in this place in the code tells the newer JavaScript that it can use and enforce newer JavaScript standards.

11. Assignment using var and let
In JavaScript, a declaration using the var keyword, no matter how many times it appears in a routine, is lifted to the top level and refers to one and only one variable (a source of bugs if the programmer expects block scope).

The let keyword requires a newer JavaScript system and does have block scope and can be used in a lambda closure. This becomes important in many web systems with dynamically generated controls with events (e.g. mouse clicks).

12. Using var
Here is the result in JavaScript using var which is not as expected. Note: This code would not work on certain browsers using older implementations of JavaScript. It does work using the JavaScript used to generate these examples (that is, node.js JavaScript).

Here is the JavaScript code.

Here is the output of the JavaScript code.


13. End of page