Using destructuring for function arguments

Matthew Robb matthewwrobb at gmail.com
Sat May 31 12:40:15 PDT 2014


Seems like any identifiers in the arguments should always be defined in
scope before ever considering what they will be assigned.
On May 31, 2014 11:59 AM, "Nicholas C. Zakas" <standards at nczconsulting.com>
wrote:

> I've been playing around with using destructuring as function arguments
> and have come across some odd behaviors that I'm not sure are intentional
> (or perhaps, not to spec). For context, consider the following function:
>
> ```
> function setCookie(name, value, { secure, path, domain, expires }) {
>     console.log(secure);
>     // ...
> }
>
> // called as
> setCookie("type", "js", {
>     secure: true
> });
> ```
>
> What happens here:
> * `secure === true`
> * `path === undefined`
> * `domain === undefined`
> * `expires === undefined`
>
> I'd say all of that behavior is as expected. However, if I omit the third
> argument completely, things get a bit strange:
>
> ```
> setCookie("type", "js");   // throws error at console.log
> ```
>
> What happens here is that none of `secure`, `path`, `domain`, `expires`
> are defined. I can use `typeof` on them to protect against this, but then I
> end up with some lousy looking code:
>
> ```
> function setCookie(name, value, { secure, path, domain, expires }) {
>
>     if (typeof secure !== "undefined") {
>         // use it
>     }
>
>     if (typeof path !== "undefined") {
>         // use it
>     }
>
>     if (typeof domain !== "undefined") {
>         // use it
>     }
>
>     if (typeof expires !== "undefined") {
>         // use it
>     }
>
>     // ...
> }
> ```
>
> My first thought was that this behavior made sense, since no destructuring
> can happen on undefined. However, the workaround for dealing with that
> behavior seems a bit heavy-handed.
>
> I thought perhaps I could assign a default value, and that would solve the
> problem:
>
> ```
> function setCookie(name, value, { secure, path, domain, expires } = {}) {
>     console.log(secure);
>     // ...
> }
> ```
>
> Unfortunately, that resulted in a syntax error in Firefox. Traceur seems
> to have no problem with it.
>
> So I really have two questions:
>
> 1. Who is right about assigning a default value to a destructured
> parameter, Firefox or Traceur?
> 2. Is the behavior of not having any bindings for destructured parameter
> properties correct? And if so, is it desirable?
>
> Thanks.
>
> --
> ___________________________
> Nicholas C. Zakas
> http://www.nczonline.net
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20140531/4352f4f3/attachment.html>


More information about the es-discuss mailing list