Another Reduce() Question. Using || when making objects from arrays

feeling fresher today back on it never gonna stop!

am going though some more reduce stuff and just want some clairty on what || symbol is doing within the reducers
heres one example (it is also used in others ive been going though)

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

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

okay so i understand its saying if the fruit does not exist as a key in the object put it there and + 1 what i dont understand is the use of the || like how to think of it. ive only used it as an or operator and it doesnt feel like there is sense in using the word or there (maybe im wrong!) i just want to feel more confitable using it a way to remember to include it if you will.
its saying if fruit doent exist put it there set to zero and plus one
if it does already exist just plus one.
obviosly the || is needed but i dont really know how to explain why its needed to myself.

If tally[fruit] has a truthy value than its value is the value that the whole expression inside the parenthesis will take, if it has a falsy value (undefined, null, 0 etc) then the value of the whole expression in round parenthesis will be 0


Think of tally[fruit] || 0 as tally[fruit] ? tally[fruit] : 0

It is very useful when used in initializer.

you should also read

1 Like

thanks guys! very useful stuff XD

what is the ? called i think i need to relook it up 2 refresh myself lots of info going it not all sticking

That is the ternary operator: (condition) ? (If true do this) : (else do this)

(tally[fruit] || 0) It is a hidden if else. If tally[fruit] exist will be count with 1, otherwise will be 0.