12

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?

1
  • Didn't you miss the property names in that arguments "object declaration"? Commented May 29, 2012 at 19:27

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

5 Comments

some links died
@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], [2]
@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 :-)
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 There are no "properties in the parameter variable". The destructuring targets become local variables in the function, just like normal parameters.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.