0

I know there are some similar questions to this one, but my one concerns just a particular solution to the problem (the problem: for a string input, return an object that counts the number of times each character (key) occurs in the string (value)):

function countAllCharacters(str) {
 var obj = { };
 for (var i = 0, j = str.length; i < j; i++) {
   obj[str[i]] = (obj[str[i]] || 0) + 1;
   }    return obj
 }

I'm familiar with object notation and looping through an array, but I'm not sure what is going in line 4, where the code is presumably assigning some numeric value to the object key. Specifically, I don't get this bit:

(obj[str[i]] || 0) + 1;

Thanks for your help!

user211309
  • 99
  • 1
  • 13
  • 3
    `(obj[str[i]] || 0)` will return `obj[str[i]]` if it is some truthy value and 0 if it is not. Thus, if `obj[str[i]]` is truthy the entire expression will return `obj[str[i]]+1`, and if it is not it'll just return `0+1` – Hamms May 12 '17 at 00:29
  • 1
    This is a dup: http://stackoverflow.com/questions/881085/count-the-number-of-occurrences-of-a-character-in-a-string-in-javascript – funcoding May 12 '17 at 00:30

0 Answers0