Array Generics and null

Dean Edwards dean at
Mon Mar 24 10:31:27 PDT 2008

Mike Shaver wrote:
> On Sun, Mar 23, 2008 at 2:44 AM, Dean Edwards <dean at> wrote:
>>  I'd prefer Array.forEach(null) to do nothing, just like for (var i in
>>  null) does nothing. I'm prepared to be convinced otherwise. :-)
> forEach isn't like enumeration, though, it's like the more common
> Array pattern of
> for (var i = 0; i < a.length; i++) {
>   doIt(a[i]);
> }
> And if a is |window|, you get exactly the same effects, no?  If a is
> null, you get an exception, which I think is probably not what we
> want.  FWIW, ES3 specifies that |for (var i in null)| throw a
> TypeError (see 12.6.4 step 3, and 9.9), but we and AFAIK all other
> browsers intentionally diverge; we made that change relatively
> recently, I think in FF2's timeframe.  I expect that ES4 will specify
> the non-throwing behaviour, because an exception is just too harsh a
> punishment for trying to iterate over null or undefined.

Like I said previously, Array.generic delegating to is an artefact of the way JS grew as a 
language. Generics were added later. If generics were originally 
specified then Array.prototype.generic would delegate to Array.generic.
 From the ES4 reference implementation

prototype function forEach(eacher, thisObj=null) {
   Array.forEach(this, eacher, thisObj);

It seems we have three choices for Array.forEach(null)

1) Do nothing
2) Throw an exception
3) Use the current object and iterate that

I prefer the first one, throwing an exception is acceptable too but the 
last one is counter-intuitive IMO.


More information about the Es4-discuss mailing list