David Zalk
David Zalk

Reputation: 29

What is the purpose of adding brackets at the end of this reduce method?

I am reading Eloquent Javascript and I am on chapter 5, Higher order functions. One of the Problems at the end was to flatten an array of multiple arrays. The Book solution gives the solution as an arrow function, and it has brackets at the end of the line of code. I want to know why they have to be there because i wrote the same code without the brackets and it returned the same value. I just wanna know why we use the brackets so I can understand the reduce method better, and not mess anything up in the future. Here is the 2 versions, they both work.

I looked through various forums, Stack, MDN, w3, could not find an explanation.

var arrays = [[1,2,3],[4,5],[6,7],[8,9]];

console.log(arrays.reduce(function(a, b) { return a.concat(b)},[]));
// Brackets----------------------------------------------------^^^
console.log(arrays.reduce(function(a, b) { return a.concat(b)}));
// No Brackets-----------------------------------------------^^^

//result = [1, 2, 3, 4, 5, 6, 7, 8, 9]

So the result is the same for both, but I know that there has to be a reason that these brackets are here, I want to know why and what the purpose of them is. Thanks in advance!!

Upvotes: 0

Views: 704

Answers (1)

Jaybird
Jaybird

Reputation: 541

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

initialValue:

Value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used. Calling reduce() on an empty array without an initial value is an error.

Example where the initialValue matters:

var fruit = ['apple', 'banana', 'banana', 'apple', 'banana', 'apple', 'apple', 'apple'];

console.log(fruit.reduce(function(a, b) { a[b]++; return a; },{apple: 0, banana: 0}));
// { apple: 5, banana: 3 }

console.log(fruit.reduce(function(a, b) { a[b]++; return a; }));
// apple

So you see in this scenario, if I give a nice initial value, I get what I want - the count of each type of fruit. Not giving an initial value here just makes the code randomly spit out the word apple.

Upvotes: 2

Related Questions