3

I swa this arrow function in a Redux example:

export const addTodo = (text) => {
  return {
    type: 'ADD_TODO',
    id: nextTodoId++,
    text
  }
}

I was wondering whether I can get rid of the extra layer of { return ...; }, essentially getting rid of the block?

For illustration, the following two arrow functions are the same:

const fn = (a) => a + 1;
const fn = (a) => { return a+1; };

and I can strip the return from the second, more verbose version.

But when I do the same to the Redux example and strip the return layer, I get an error:

SyntaxError: repl, unexpected token, expected ; ...

It seems that there is some confusion between the {} in the object literal and code blocks. Is there a way to remove this this extra layer of return here?

JJJ
  • 32,902
  • 20
  • 89
  • 102
thor
  • 21,418
  • 31
  • 87
  • 173

2 Answers2

1

you can prevent the confusion by adding extra parentheses like this -

export const addTodo = (text) => (
  {
    type: 'ADD_TODO',
    id: nextTodoId++,
    text
  })

hope that helped :)

Ran Sasportas
  • 2,256
  • 1
  • 14
  • 21
0

Also you can use more explicit Object.assign for (arguably) better readability:

const addTodo = text => Object.assign({
  type: 'ADD_TODO',
  id: nextTodoId++,
  text
})
Egor Stambakio
  • 17,836
  • 5
  • 33
  • 35