What do curly braces inside of function parameter lists do in es6?

JavascriptEcmascript 6

Javascript Problem Overview


I keep seeing functions that look like this in a codebase I'm working on:

const func = ({ param1, param2 }) => {
  //do stuff
}

What exactly is this doing? I'm having a hard time finding it on google, because I'm not even sure what this is called, or how to describe it in a google search.

Javascript Solutions


Solution 1 - Javascript

It is destructuring, but contained within the parameters. The equivalent without the destructuring would be:

const func = o => {
    var param1 = o.param1;
    var param2 = o.param2;
    //do stuff
}

Solution 2 - Javascript

This is passing an object as a property.

It is basically shorthand for

let param1 = someObject.param1
let param2 = someObject.param2

Another way of using this technique without parameters is the following, let's consider then for a second that someObject does contain those properties.

let {param1, param2} = someObject;

Solution 3 - Javascript

It is an object destructuring assignment. Like me, you may have found it surprising because ES6 object destructuring syntax looks like, but does NOT behave like object literal construction.

It supports the very terse form you ran into, as well as renaming the fields and default arguments:

Essentially, it's {oldkeyname:newkeyname=defaultvalue,...}. ':' is NOT the key/value separator; '=' is.

Some fallout of this language design decision is that you might have to do things like

> ;({a,b}=some_object);

The extra parens prevent the left curly braces parsing as a block, and the leading semicolon prevents the parens from getting parsed as a function call to a function on the previous line.

For more info see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

Beware, key errors during object destructuring assignment do NOT throw; you just end up with "undefined" values, whether it's a key error or some other error that got silently propagated as 'undefined'.

> var {rsienstr: foo, q: bar} = {p:1, q:undefined};
undefined
> foo
undefined
> bar
undefined
> 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNathanView Question on Stackoverflow
Solution 1 - JavascriptJames ThorpeView Answer on Stackoverflow
Solution 2 - JavascriptOz LodriguezView Answer on Stackoverflow
Solution 3 - JavascriptAndrew WagnerView Answer on Stackoverflow