Ad

Braces Around Params -- Why?

- 1 answer

I ran across this in a tutorial:

const Todos = ({todos}) => (
  <div>
    <h1>Todos</h1>
    {todos.map(todo => <p key={todo}>{todo}</p>)}
  </div>
)

Why does parameter have braces around it? If I'd written it myself, the first line would look like this:

const Todos = (todos) => (...

Is this some wacky new ES6 syntax that I simply can't find documented?

Ad

Answer

This is the syntax for parameter object destructuring, which was introduced as part of ECMAScript 2015. The Todos function doesn't define a single parameter named todos, but instead accesses the todos property of an object that's passed in (and that is immediately destructured).

It is roughly equivalent to the following version:

const Todos = (_param) => {
  let todos = _param.todos;
  return (
    <div>
      <h1>Todos</h1>
      {todos.map(todo => <p key={todo}>{todo}</p>)}
    </div>
  );
};

Check out Destructuring and parameter handling for more information on destructuring.

Ad
source: stackoverflow.com
Ad