9

If I want to call a function like this:

moo({ a: 4 });

Normally I'd have to phrase my function definition like this:

function moo(myArgObj) {
    print(myArgObj.a);
}

But this awesome syntax is totally valid in spidermonkey for defining functions:

function moo({ a, b, c }) { // valid syntax!
    print(a); // prints 4
}

What is this feature?

Kyll
  • 6,830
  • 6
  • 39
  • 56
Verdagon
  • 2,156
  • 3
  • 19
  • 34

1 Answers1

6

It's called destructuring. You might find the most info at MDN: Destructuring assignment (especially see Unpacking fields from objects passed as function parameter).


The ECMAScript standards discussion can be found on their wiki page, also interesting might be this blog post at dailyjs.

str
  • 33,096
  • 11
  • 88
  • 115
Bergi
  • 513,640
  • 108
  • 821
  • 1,164
  • @NguyễnXuânHoàng Thanks, but I'm not sure whether they're dead or just unresponsive (especially the ecmascript wiki is often down). You can find both of them in the internet archive though: [\[1\]](https://web.archive.org/web/20150219021117/http://dailyjs.com:80/2011/09/12/destructuring/), [\[2\]](https://web.archive.org/web/20161222134616/http://wiki.ecmascript.org/doku.php?id=harmony:destructuring) – Bergi Nov 22 '17 at 07:17
  • @NguyễnXuânHoàng And of course, more than five years later, the drafts have made their way into the standard, and there are much better resources on the topic available today :-) – Bergi Nov 22 '17 at 07:18
  • destructuring explains how the values of the properties in the passed object get assigned to the properties in the parameter variable but it doesn't explain how those properties can be accessed in the function without qualification - ie. how the whole business works with an unnamed parameter. Any idea where that comes from ? – Bob Jun 28 '19 at 13:21
  • @Bob There are no "properties in the parameter variable". The destructuring targets become local variables in the function, just like normal parameters. – Bergi Jun 28 '19 at 14:02