JS reduce() method syntax understanding

Viewed 83

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?

3 Answers

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.

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);

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}

Related