Luke
Luke

Reputation: 20090

Why use DOMStringList rather than an array?

I've recently discovered the DOMStringList, which can be found in an IndexedDB's list of store names. It seems like a DOMStringList is just a simplified version of an array, which has only two methods item() and contains(). There is no useful methods like indexOf, filter, forEach that you'll find on an Array. Why use this kind of object? What are DOMStringList's advantages?

Upvotes: 10

Views: 4770

Answers (1)

Domenic
Domenic

Reputation: 112917

The existence of DOMStringList is a historical accident. Today, in modern APIs, the same use cases are met by using an Array instance.

It was introduced into web APIs because we needed something array/list-like, that cannot be modified. The "cannot be modified" part is important, because there's no good answer for what would happen to a modifiable array in scenarios like

db.objectStoreNames.push("foo");
db.objectStoreNames.push(notAString);
db.objectStoreNames.shift();

At the time the first API using DOMStringList was introduced, the people designing the API did not know how to make this work with Arrays. So, they designed DOMStringList. It was used for a couple of APIs, namely location.ancestorOrigins and db.objectStoreNames.

But then, the people designing such web APIs figured out how to introduce non-modifiable arrays. This actually took two separate tries:

The difference between these two is that frozen Arrays cannot be modified, even by the browser; whereas proxies around Arrays can be modified by the browser. (Or even by the web developer, if the spec in question allows that.)

So, can we move everything using DOMStringList to use one of these modern solutions? No. Because there is code in the wild which depends on db.objectStoreNames.item() and db.objectStoreNames.contains() working, and that would break if we moved to actual Array instances, which don't have those methods.

So we might need a third Array wrapper type if we want to fully obliterate the legacy array-like classes from the web platform, and start using true Arrays. It would be a subclass of Array, with an extra method or two, and possibly a proxy wrapped around that. Nobody has yet made moves in that direction.

(Other legacy array-like classes, you say? Yes: in addition to DOMStringList, we have TouchList, AnimationNodeList, CSSRuleList, DOMRectList, FileList, ... see this list of classes on the web platform with an item() method, most (but not all) of which are of this sort.)

Upvotes: 29

Related Questions