An array destructing specification choice

Allen Wirfs-Brock allen at wirfs-brock.com
Sat Nov 5 09:49:40 PDT 2011


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?


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

> 
> If of course there had been the case of strict pattern matching (like e.g. in Erlang in this case), then it should be an error.


Allen


More information about the es-discuss mailing list