2

Given the following react-redux code:

const TextListContainer = ({ items, actions }) => (
    <TextList items={items} actions={actions} />
)

Why are normal brackets used here instead of curly brackets?


To further illustrate my question:

NORMAL FUNCTION:

const someFn = something => {
    //...
}

BRACE STYLE FUNCTION:

const someFn = something => (
    //...
)

This style of code is copied from here: https://github.com/reactjs/redux/blob/master/examples/todomvc/src/containers/App.js

Alex
  • 2,651
  • 2
  • 25
  • 45
  • 1
    Learn about destructuring or about how arrow function syntax actually works, depending on which braces you're asking about. – SLaks Nov 30 '17 at 15:50
  • [MDN link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Unpacking_fields_from_objects_passed_as_function_parameter) – Pointy Nov 30 '17 at 15:53
  • Possible duplicate of [Curly Brackets in Arrow Functions](https://stackoverflow.com/questions/35440265/curly-brackets-in-arrow-functions) – Dane Nov 30 '17 at 15:54
  • I know about destructuring and arrow syntax, how this is an example of destructuring? – Alex Nov 30 '17 at 15:55
  • 1
    It's not destructuring, it is shorthand for returning a value – Patrick Hund Nov 30 '17 at 17:44
  • Thanks for clearing that up Patrick, would be good if people read the question first, will remove all mention of destructuring from the question. – Alex Nov 30 '17 at 18:12

2 Answers2

9

() => something, where something doesn't start with {, returns something.

With () => {, { is interpreted as the start of a function body, so you have to explicitly return something. To get around this, e.g. if you wanted to return an object, you can use (:

() => ({ some object })

Using it in other situations is a question of consistency.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
  • Thanks for the explanation, this makes sense now, I am still unsure why everyone was pointing to destructuring in the comments above.. – Alex Nov 30 '17 at 16:07
  • No problem, I guess they skimmed over your question and saw the `{ items, actions }` in the first example, which destructures the props object. – Tom Fenech Nov 30 '17 at 16:10
2

Basically {} is used when there is function body and you need to return a particular value based on the computations in the function. A simple example of a function to add 1 if value is more than 10 else subtract 1 .

(value) => {
  if(value > 10){
    return value + 1; 
  }
  return value - 1;
}

On the other hand if there is really a simple function like returning a boolean value.you could do something like this:

(num) => (num > 100)

returns a boolean. Simple and clean.

Rahul
  • 702
  • 2
  • 8
  • 26