An array destructing specification choice

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


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.

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.

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.

IMO.

Dmitry.


More information about the es-discuss mailing list