Re: DOM collections index out of bounds and JavaScript.

On 10/19/10, Scott Shattuck <idearat@mindspring.com> wrote:
> Seems to me that when you access a slot that in some sense "doesn't exist"
> it should return undefined, not null. There are plenty of semantic cases (is
> this attribute defined but currently unset, or not defined at all) where the
> difference can be significant. I realize not all languages support the
> distinction, but JS does and it's actually a useful feature.
>

How useful would it be here?

Could specification(s) be changed to allow property access to return
undefined and still allow `item()` to return null? That's what
implementations mostly do now, right?

I don't generally write code that accesses an indexed property of a
collection unless I know that the element at that index exists. I
recall now a piece of code -- jQuery, in fact-- wherein an "optimized"
`for` loop was implicated in an out-of-bounds property access on a
StyleSheetList object. The result was a javascript error in MSIE. The
author blamed MSIE for that, but when I saw that code, I realized that
with as much js as I'd written, and even in using MSIE's collection
equivalent of styleSheetList, that I'd never tried to access an
out-of-bounds index off it. I'd always done like so:

for(var i = 0; i < list.length; i++) {
  if( list[i].title == "foo") {
    return list[i];
  }
}

And so with that code, there would never be an out-of-bounds access.

I forget the thread title but I'll try and dig it up...

FOund:
<http://groups.google.com/group/comp.lang.javascript/browse_thread/thread/41e87ec5cbcbdaff/785e03f0701777c0?>

Althoug it demonstrates the javascript error in calling item method
with an out-of-bounds index in IE, that thread (like so many others)
shows how badly authored the jQuery library is more than anything.

And so while it would be nice for `item` and property access to have
the same result, how much benefit would this actually add to the web
to know that, `obj.item(9999) === null`?

Property access on any of the various collection objects is specified
to return `null` when the property by that index is not resolved. But
instead it either results `undefined` or throws an error (MSIE). Since
behavior for collections (item, callability, etc) is specified in
various specifications, and since spec authors and page authors want
consistent behavior, is it worth considering specifying a base
"Collection" in one place?

Garrett

Received on Tuesday, 19 October 2010 18:28:35 UTC