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

29,631

Solution 1

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

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

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
> 
Share:
29,631

Related videos on Youtube

Nathan
Author by

Nathan

Updated on July 08, 2022

Comments

  • Nathan
    Nathan almost 2 years

    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.

  • Nathan
    Nathan almost 8 years
    Just to make sure I'm understanding correctly, basically this means that an object containing those properties would be passed into the function, and then within the function, the properties can automatically be accessed just using their name?
  • James Thorpe
    James Thorpe almost 8 years
    @Nathan Yes, see specifically the section on Object destructuring. Note however that updates to the variables won't update the original object properties - it's not like it's creating a reference to the original value.
  • lsborg
    lsborg over 4 years
    @JamesThorpe it would be better to link to developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…