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

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.

Answers:

Answer

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;
Answer

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
> 
Answer

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
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.