3 ms·
Javascript array indexing is a MESS. This array["foo"] = "bar" is valid javascript.
by cogman10 5y ago
Javascript array indexing is a MESS. This
array["foo"] = "bar"
is valid javascript.
- Osiris 5y agoWhy does this make it a mess? Array already has a bunch of properties that aren't elements in the Array that come from the prototype, like join and slice. Your example is just adding a custom property to the array.
- cogman10 5y agoBecause in most other languages, an array is an enumeration of values. That's it. In Javascript, arrays are actually dictionaries. But not full dictionaries, rather just dictionaries that can have either a string or numeric key. It's messy because an array in javascript isn't just "an array" it's this mismesh of features that are unexpected to a new-to-javascript developer. Unexpected is the enemy of readable code.
- gsnedders 5y agoNo, arrays are just objects with a magic "length" property (technically: a special [[DefineOwnProperty]] internal method which sometimes also mutates "length"). Like objects, they only support strings as keys. c.f. https://tc39.es/ecma262/#sec-array-exotic-objects https://tc39.es/ecma262/#sec-array-exotic-objects
- ironmagma 5y agoIt’s only unexpected if you’re bringing in expectations from somewhere else. Coming from JS as basically my first language, it was surprising and a bit annoying that you couldn’t assign properties to hardly anything in other languages, even functions in languages where functions were supposedly first class.
- londons_explore 5y agoarray["at"] = "lunchtime"; Is also valid javascript... And will break functionality in this proposal!
- runarberg 5y agoI think this is the point of the stage 3 proposal. Browser makers start implementing the feature and releasing it in the development and beta versions of their browsers. Then if the users of the experimental features start noticing that webpage break, the proposal will get an update. If I remember correctly, this exact thing happened to `Array.prototype.flatten` which got renamed to `Array.prototype.flat` after it was realized that the former broke a lot of legacy webpages (and after a long discussion of `Array.prototype.smoosh`[1]) 1: https://developers.google.com/web/updates/2018/03/smooshgate https://developers.google.com/web/updates/2018/03/smooshgate
- IainIreland 5y agoIn fact, it already happened to this proposal, which started life as `Array.prototype.item` before it turned out that some libraries were using the presence of a `.item` property to duck-type DOM collections: https://github.com/tc39/proposal-relative-indexing-method#web-incompatibility-history https://github.com/tc39/proposal-relative-indexing-method#we...