Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

braces around params -- why? [duplicate]

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?

like image 231
Ethan Clark Avatar asked Feb 08 '23 00:02

Ethan Clark


1 Answers

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.

like image 57
Marius Schulz Avatar answered Feb 11 '23 01:02

Marius Schulz