Generators in JavaScript 1.7

Posted on Wed 28 February 2007
While looking at some JavaScript code from Joost's client software yesterday (you should all know by now that it's based on the Mozilla platform), I found some unusual statements which led me to discover the new features in JavaScript 1.7.

It's actually not that new since it's been there since Firefox 2.0, but pretty cool anyway. JavaScript has borrowed some nice features of Python, namely generators and multiple-value returns.

The classical Fibonacci suite written with JavaScript generators:
function fib() {
  var i = 0, j = 1;
  while (true) {
    yield i;
    [i, j] = [j, i + j];
  }
}

var g = fib();
for (let i = 0; i < 10; i++)
  print(g.next());

The multiple-value returns is actually a subset of the more general destructuring assignment which I find a bit too-much, since taken to the extreme it actually makes the code less readable... unless you have some experience with Prolog unification :-)

Anyway, it's nice to see JavaScript evolve. IE won't have it for the 5 (or more) years to come though...


From pen & paper to Web 2.0

GeoRSS support in Google Maps