fail-fast object destructuring (don't add more slop to sloppy mode)

Allen Wirfs-Brock allen at wirfs-brock.com
Thu Jan 3 16:33:23 PST 2013


On Jan 2, 2013, at 7:58 PM, Brendan Eich wrote:

> I think we can do this now. Allen should weigh in. Hope to hear from Andreas R. soon too!
> 
> Apologies for the long thread, and thanks to Herby for interaction that clarified many things. Perhaps I should resummarize:
> 
> The best new-new plan to avoid adding slop is to revise ES6 destructuring thus:
> 
> 1. No ToObject(RHS).
> 2. Exception on missing property selected without a ?-suffix.
> 3. ?-suffix allowed on any pattern, imputing undefined deeply instead of refuting.
> 4: the ? is a separate lexeme from the : in long-hand patterns.
> 
> How's that?
> 

I'm fine with points 2-4.  However, I think no ToObject(RHS) would be a mistake.  Here's why:

In almost all other situations where an object is needed, a primitive value (including a literal) can be used.  This includes contexts that use the dot and [ ] property access operators. Essentially, in all object appropriate situations primitive values act as if they were objects. This is important in that in most cases it allows ES programmers to ignore distinctions between objects and primitive values.

Destructuring is frequently described as simply a de-sugaring over property access in assignments and declarations.  

let {length: len} = obj;

is most easily explained by saying that it is equivalent to:

let len = obj.length;

But if the ToObject is eliminated from the RHS then this desugaring equivalence is no longer valid in all cases.  The obj.length form would work fine if the value of obj was a string but the destructuring form will throw.  This breaks the general ES rule that you can use a primitive value in any context where an object is required.  It is the sort of contextual special case that developers hate and which makes a language harder to learn. Consistency is important.

Finally, note that now with exceptions on missing properties (without ?) it is likely that most situations where a primitive value is erroneously used on the RHS will throw anyway simply because the primitive wrapper probably won't have the requested property. So, removing the ToObject just creates inconsistency without adding much in the way of error detection.

Allen 


More information about the es-discuss mailing list