Implicit coercions suck, and IMO it would be better if destructuring didn't add 
new ones to JS. In the current draft spec, I believe if you match an object 
destructuring pattern against a non-object or an object that doesn't have one 
or more of the properties, it quietly proceeds -- masking what is quite likely 
an error:

    var { foo, bar } = getFooAndBar();

If getFooAndBar() doesn't produce an object with foo and bar properties, 
there's probably something going wrong! And most of the time when you do want 
to be forgiving (say, in a function signature, or when reading a configuration 
file), you have a specific default value you want to provide, which can be 
specified with the default syntax:

    var { foo = defaultFooValue, bar = defaultBarValue } = getFooAndBar();

I'd like to propose the following changes:

(a) Throw when matching null, undefined, booleans, or strings against an object 
pattern. (I don't propose throwing when matching a string against an array 
pattern, however, since strings behave structurally like read-only arrays.)

(b) Allow a shorthand "?" prefix for properties in an object destructuring 
pattern. This is simply shorthand for defaulting to undefined. IOW, the 
following are all equivalent:

    var { ?foo } = getFoo();
    var { foo = undefined } = getFoo();
    var { foo: foo = undefined } = getFoo();
    var { ?foo: foo } = getFoo();

Note, however, that (b) is not strictly necessary to get the fail-soft 
behavior. You can always write the explicit default. But it makes it 
considerably more convenient to get the fail-soft behavior when you want it -- 
only one character more expensive than fail-fast.

Dave

_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to