0

ES6 arrow function allows writing one-line functions without a return statement. However, if I try to return an object this way (without any other instruction), ES6 gets confused and thinks that I'm trying to surround my function with curly braces.

example:

const foo = (a)=>{a}
foo(1) #returns undefined instead of {a:1}

if I do

const foo = (a , b)=>{a , b}
foo(1 , 2) #returns undefined

and

const foo = (a , b)=>{a : a , b :  b}
foo(1 , 2) # SyntaxError: Unexpected token

So is it impossible to return an object litteral from an arrow function without the return statement?

Jad S
  • 2,705
  • 6
  • 29
  • 49
  • 2
    const foo = (a , b)=>({a,b}) – Andrey Sidorov Jan 27 '17 at 05:47
  • 1
    `{}` followed by `=>` defines it as a block. You can do `=>{ return {a:a} }` – Rajesh Jan 27 '17 at 05:47
  • 1
    For the single-argument one: `const foo = a => ({a})` – Amadan Jan 27 '17 at 05:48
  • @Rajesh the question specified no return statement. But yea parenthesis are the way, although I must say that I find this lack of return statement makes ES6 hard to read sometimes. This case caused a bug and took me ages to find. Makes me think we've traded readability for conciseness. – Jad S Jan 27 '17 at 05:56
  • 1
    `#returns 1, not {a : 1}` - no, that returns undefined – Jaromanda X Jan 27 '17 at 05:57
  • @JadS when you define a block, you **will have to** use `return` to return a value. **[JSFiddle](https://jsfiddle.net/RajeshDixit/oc1Lkx6s/2/)** – Rajesh Jan 27 '17 at 06:00
  • 1
    Readability is subjective to a some degree and also context dependent. I personally find `arr.reduce((sum, x) => sum + x)` more readable than `arr.reduce(function(sum, x) { return sum + x; })`. Less syntactic noise. – Felix Kling Jan 27 '17 at 06:33

0 Answers0