Hacker News new | ask | show | jobs
by Spivak 1841 days ago
The problem with JS language development is the mountain of code that it would break if you do anything except append features.

    array[-1] = “foo”
This already works in JS but doesn’t do what you expect and just assigns the property.
2 comments

To be clear this is equivalent to array["-1"] (unless you do horrible things overriding the built in types). Since arrays are "just" objects in JavaScript it is completely valid to add a property called "-1" to it.
Javascript array indexing is a MESS. This

    array["foo"] = "bar"
is valid javascript.

    array["at"] = "lunchtime";
Is also valid javascript... And will break functionality in this proposal!
I 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

In 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#we...

Why 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.
Because 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.

No, 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

It’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.