Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

comparing two reduce() methods

const fruitBasket = ['banana', 'cherry', 'orange', 'apple', 'cherry', 'orange', 'apple', 'banana', 'cherry', 'orange', 'fig' ];

why does this -

const count = fruitBasket.reduce((tally, fruit) => {
  if (!tally[fruit]) {
    tally[fruit] = 1;
  } else {
    tally[fruit] = tally[fruit] + 1; //??//
  }
  return tally;
}, {});

is equal to this -

//const count = fruitBasket.reduce( (tally, fruit) => {
//  tally[fruit] = (tally[fruit] || 0) + 1 ;
//  return tally;
//} , {})

i dont seem to understand - (tally[fruit] || 0) + 1 ;

2 Answers

// At the start of the reduce, tally is an empty object: {}
{} //tally
// if the first entry is 'banana', then we begin to run the function on 'banana'.
// We're going to set tally['banana'] to the evaluated value of (tally['banana'] || 0 ) + 1
tally['banana'] || 0 //Here either tally[fruit] exists in which case we grab the value 
// associated with the 'banana' key, OR not, in which case we get 0. 'banana' 
// doesn't exist on tally because tally is empty, so we get 0.
// If there isn't a key on the object with any said value, the right side of the 
// OR statement will be the result of that evaluation.
// you can try this yourself:
//**********
const x = {}
x['hello'] || 1 // 1

const x = {}
x['hello'] || NaN//  NaN

const x = {}
x['hello'] || false //  false

// On the other hand, if the key exists, the left side will always be the result
const x = {'hello': 2}
x['hello'] || false //  2
***********/
+ 1 // we add 1 to the determined value, so 0 + 1 = 1.
tally[fruit] = 1 // since 'banana' isn't a key on tally, we create one, and assign the value 1.
{'banana': 1} // tally
// Now we move on to the next value in the array, lets say it's also 'banana'.
tally['banana'] = (tally['banana'] || 0 ) + 1 // evaluates to tally['banana'] = 1 + 1
{'banana': 2} // tally

Hope that makes sense!

thanks :)