I feel this syntax is odd ally[fruit] = (tally[fruit] || 0) + 1
. I’ assuming the following: I’m saying that (for each iteration) in the object tally
the property fruit
has a number as value and that number increases by one each time the same fruit is visited.
questions: || 0
is a way to initialize that value to zero (as a var-counter)?
wouldn’t be another (more readable) syntax for that purpose?
const fruitBasket = ['banana', 'orange', 'banana' ];
//A: in obj tally, the prop fruit is equal to a num (a counter)
//B: || 0 is an initialization of fruit-value to zero
const fruit_tally = arr => {
const response = arr.reduce(function(tally, fruit){
tally[fruit] = (tally[fruit] || 0) + 1 //A, B
return tally;//returning obj
}, {})//initializaing obj
return response;
}
fruit_tally(fruitBasket);//--> { banana: 2, orange: 1 }