2

I have the following two codes one could run from any browser.

Code1:

let prices = [1, 2, 3, 4, 5];
let result = prices.reduce( (x,y)=>{x+y} ); // Reduce data from x to y.
console.log(result);

Code2:

let prices = [1, 2, 3, 4, 5];
let result = prices.reduce( (x,y)=>x+y ); // Reduce data from x to y.
console.log(result);

The first code doesn't work but the second does.

Why would the braces ({}) make it not to work? Aren't they part of an implicit function? Or this braceless syntax is just something unique to the reduce() method?

Ram Segev
  • 2,563
  • 2
  • 12
  • 24
Osi
  • 1
  • 3
  • 9
  • 30
  • 1
    You need to explicitly mention 'return'. Please refer to 'Function Body' & 'Returning object literals' sections to understand more about arrow functions. [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Function_body] – Sri Nov 26 '17 at 12:37

3 Answers3

3

In the first one the return statement is missing:

let prices = [1, 2, 3, 4, 5];
let result = prices.reduce( (x,y)=>{return x+y;} ); // Reduce data from x to y.
console.log(result);

In the second example return is implicit.

Dávid Molnár
  • 10,673
  • 7
  • 30
  • 55
  • Hmm, interesting. Why do we need the `return` in the explicit versioon in the first place? I rarely use `return` in JS, only when I want to stop a function in a certain place in its scope, and move on to the next part of my code. – Osi Nov 26 '17 at 14:51
  • 1
    Because the `reduce` function needs it. In every iteration you need to return the next accumulator, which then will be the first argument for the following iteration. – Dávid Molnár Nov 26 '17 at 14:54
3

The first doesn't work because the {} are present. In ES6 the => can serve as a replacement for the return keyword if the next thing following the => is without {}.

In the case where the {} is supplied after the => you'd need to explicitly use the return keyword.

In code 1, you'd need to modify it slightly like below:

let prices = [1, 2, 3, 4, 5];
let result = prices.reduce( (x, y) => { return x + y }); // Note the return keyword
console.log(result);
codejockie
  • 9,020
  • 4
  • 40
  • 46
3

The second example works because without the braces, x+y is returned implicitly. If you include the braces, you must explicitly return the value, e.g. {return x+y}

Dexygen
  • 12,287
  • 13
  • 80
  • 147
  • The real tragedy is that `() => {}` does not return an object. – Aluan Haddad Nov 26 '17 at 12:42
  • The issue is that braces are over-loaded -- they can either be used for function bodies, or object literals. It only makes sense that for arrow functions they must be interpreted as function bodies, because not all arrow functions will just return a value, but might contain other statements as well. – Dexygen Nov 26 '17 at 13:31
  • I upvoted it. I was just making a comment – Aluan Haddad Nov 26 '17 at 22:38