Letting RegExp method return something iterable?

Claude Pache claude.pache at gmail.com
Tue Aug 27 05:24:43 PDT 2013

Le 27 août 2013 à 01:23, Brendan Eich <brendan at mozilla.com> a écrit :

> Andrea Giammarchi wrote:
>> Is it very useful because you wrote for instead of while ?
>> ```javascript
>> while (m = re.exec(str))
>>  console.log(m[0])
>> ;
>> ```
> It is, for two reasons:
> 1. in JS only for can have a let or var binding in the head.
> 2. the utility extends to all for-of variations: array comprehensions, generator expresisons.
> /be

There is a third reason. The syntax:

for (let m of re.execAll(str) {
	// ...

has the clear advantage to express the intention of the programmer, and *nothing more*. It does not require good knowledge of the details of the language to understand what happens.

Indeed, when I read `while(m = re.exec(str))`, I really have to analyse the following *additional* points:
* `=` is not a typo for `==` (here, some annotation would be useful);
* `RegExp#exec` returns a falsy value if *and only if* there is no more match;
* `re` has its global flag set, and its `.lastIndex` property has not been disturbed.

All these tricks are unrelated to the intention of the programmer, and are just distracting points, especially for any reader that use only occasionally `RegExp#exec` with the global flag set.

In summary, citing [1]: "Don’t be clever, don’t make me think."


[1] http://www.2ality.com/2013/07/meta-style-guide.html

More information about the es-discuss mailing list