[This was originally one of my posts on r/javascript from 2 months ago. Aside from the first few sentences, no edits have been made to the contents of the post.]
I'm playing around with concepts for a Javascript-inspired programming language, and I was met with a design decision:
When destructuring an object, should we pull from the object's entire prototype chain, or only the own properties (not inherited from the prototype chain) of the object?
In other words, in the equivalent to this line of code:
let {a, c, ...rest} = {a: 0, b: 1, __proto__: {c: 2, d: 3}}
Should [a, c, rest]
be [0, 2, {b: 1, d: 3}]
, or should it be [0, <not assigned>, {b: 1}]
?
On one hand, we probably don't want to pull from the object's entire prototype chain. Imagine if, after executing let {a, ...rest} = {a: 0, b: 1}
, Object.hasOwn(rest, x)
returned true for x = isPrototypeOf
, toString
, valueOf
, etc and all of those properties were just the same functions as the ones on Object.prototype
. And imagine how inefficient destructuring would be when we have long prototype chains with many properties on each prototype.
On the other hand, in something like let {a, b, c, d} = {a: 0, b: 1, __proto__: {c: 2, d: 3}}
, we probably want c
to be 2 and d
to be 3, the same way <rhs object>.c
would be 2 and <rhs object>.d
would be 3. So we would want to pull from the entire prototype chain after all.
I decided to look at how Javascript itself dealt with this stuff (not what I actually put into the console, but it gets the general idea across):
>>> let {a, c, ...rest} = {a: 0, b: 1, __proto__: {c: 2, d: 3}}; [a, c, rest.b, rest.d]
[0, 2, 1, undefined]
It turns out that Javascript uses a hybrid approach: for ordinary properties like a
and c
, it searches the entire prototype chain. But for rest properties like ...rest
, it only uses the object's own properties.
I wasn't expecting this inconsistency between the two types of properties, but it makes sense: each individual type of behaviour is probably what you want for the corresponding type of property. You would want to search the entire prototype chain when it comes to ordinary properties, but at the same time you would want to only look at the object's own properties when it comes to rest properties.
What do you guys think? Does Javascript handle this the right way, or should it have chosen a different approach? Maybe there's another, better option than all three of the approaches that I outlined here?