An array destructing specification choice

Dmitry Soshnikov dmitry.soshnikov at gmail.com
Sat Nov 5 09:59:58 PDT 2011


On 05.11.2011 20:49, Allen Wirfs-Brock wrote:
> On Nov 5, 2011, at 9:38 AM, Dmitry Soshnikov wrote:
>
>> On 05.11.2011 20:28, Allen Wirfs-Brock wrote:
>>> In the following declaration, what should be the value of z?
>>>
>>> let [z,y,z] = {0:0, 1:1, length: 2, 2:2};
>>>
>>> should it be be 2 or undefined
>>>
>>> undefined might be reasonable because it is an array pattern, and the source object is only has two "array-like" elements
>>> 2 might be reasonable because the source object actually has a property named "2"
>>>
>>> Which alternative will be least surprising to JS programmers?
>>>
>> Since arrays may participate in the same sense as objects, e.g. for-in loop or some generic methods (e.g. o = {push: [].push}; o.push(1); o.length is created and is 1), the example can be (by logic) correct.
> The question isn't whether or not the example is correct.  It is already determined that it is valid syntax.  The question is about semantics.  Does "array" destructuring of a "array-like" object  controlled by the "length" property of the object?
>

I've perfectly understood what the question is about. Yes, I think it's 
the correct semantics (this is what I mean "correct by logic"). This of 
course only because some JS semantics is already has similar behavior -- 
e.g., again, this borrowed method [].push which creates the `length` 
property on objects.

>> Besides, since the destructuring pattern matching isn't strict (i.e. it's used only for exactly for destructuring), the example also is OK since it doesn't say "we match an array", but we only destructure a complex structure on some less complex parts, and if the pattern on the left can manage it, it's OK.
>
> Personally, I dislike calling this style of destructuring (as defined in JS) "pattern matching" because that makes it sound like it is doing much more than it really is.

It's true; this is why I often use "non-strict pattern matching" as an 
alternative term when describing the destructuring assignment. Using of 
"pattern matching" though can be familiar for others in this case, since 
in many languages (again in the same Erlang), destructuring assignment 
is just a part of the pattern-patching. But yes, I agree, it's not 
pattern matching in its full sense; but partially -- yes, why not.

Dmitry.


More information about the es-discuss mailing list