According to the MDC, the ECMA-262, 5th edition gives the implementation of forEach as:
if (!Array.prototype.forEach)
{
Array.prototype.forEach = function(fun
The probable reason is s9.9 of ECMA-262, about the abstract ToObject
operation (as mentioned by @CMS).
When called on null
or an undefined
value it forces the throwing of a TypeError
, but those are already trapped by the previous lines.
However if you were to call:
Array.prototype.forEach.call("123", func() { ... } )
this would fail if it weren't for the type coercion. In particular you can't call index in this
if this
is a string
, but you can call it on the result of ToObject
.
This text from 15.4.4.18 is probably relevant:
The forEach function is intentionally generic; it does not require that its this value be an Array object. Therefore it can be transferred to other kinds of objects for use as a method. Whether the forEach function can be applied successfully to a host object is implementation-dependent.