#### 11.4.5 Generator Expressions

11.4.5 Generator Expressions

In JavaScript 1.8,^{2 }you can replace the square brackets around an array comprehension with parentheses to produce a generator expression. A generator expression is like an array comprehension (the syntax within the parentheses is exactly the same as the syntax within the square brackets), but its value is a generator object rather than an

2. Generator expressions are not supported in Rhino at the time of this writing.

11.4 Iteration | 281

array. The benefits of using a generator expression instead of an array comprehension are that you get lazy evaluation—computations are performed as needed rather than all at once—and that you can work with potentially infinite sequences. The disadvantage of using a generator instead of an array is that generators allow only sequential access to their values rather than random access. Generators, that is, are not indexable the way arrays are: to obtain the nth value, you must iterate through all n-1 values that come before it.

Earlier in this chapter we wrote a map() function like this: function map(i, f) { // A generator that yields f(x) for each element of i for(let x in i) yield f(x); }

Generator expressions make it unnecessary to write or use such a map() function. To obtain a new generator h that yields f(x) for each x yielded by a generator g, just write this:

let h = (f(x) for (x in g));

In fact, given the eachline()generator from Example 11-1 , we can trim whitespace and filter out comments and blank lines like this:

let lines = eachline(text);

let trimmed = (l.trim() for (l in lines));