0
function maxChecker(str) {
  let final = {};
  for (let char of str) {
    final[char] = final[char] + 1 || 1;
  }

  return final;
}

If in this code I don't use the expression || 1 then my values in object is NAN kindly explain this

final[char]= final[char]+1 || 1;
ROOT
  • 11,363
  • 5
  • 30
  • 45
  • What do you expect `final[char]` to be before you add the `+1`? Also what is the goal of this code? – Ivar Jun 02 '20 at 07:34
  • Does this answer your question? [JavaScript OR (||) variable assignment explanation](https://stackoverflow.com/questions/2100758/javascript-or-variable-assignment-explanation) and [what's the result of 1 + undefined](https://stackoverflow.com/questions/14977569/whats-the-result-of-1-undefined) – Ivar Jun 02 '20 at 07:50

1 Answers1

1

What you get is NaN, because of adding to undefined a value.

console.log(undefined + 1);

But what is more a problem of this pattern, you move a error to a second step without using a falsy value, like undefined of final[char].

A better approach is to check if you get a falsy value and if so take zero as number, instead of undefined and add a value like 1 in the second step.

final[char] = (final[char] || 0) + 1;
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392