Get a count of most repeated letters in one word

I try to get an account of the most repeated letter in the word

function GreatestCount(str) { var count = {} for (var i = 0 ; i<str.length;i++) { var char = str[i]; count[char] = (count[char] || 0) + 1; } //get the largest number for the letter counts var max = 0; for (var c in count) { if (count[c] > max) max = count[c]; } return max } 

can someone explain to me why

 count[char] = (count[char] || 0) + 1;// this works count[char] += 1 // this does not work 
+4
source share
5 answers

Because

 count[char] += 1 

equally

 count[char] = count[char] + 1 

and the first time you run the code count[char] is undefined , so it’s almost the same as

 undefined + 1 // which is NaN 

The working version bypasses this case by adding safely with 0 using the || .

+7
source

Initially, count is an empty object † so it does not have a char property. Therefore, count[char] returns undefined .

And undefined + 1 creates NaN .

Therefore, you must initialize it to 0 in order for it to work correctly.

†: count is actually not an empty object, because it inherits properties from Object.prototype . It would be problematic if the char property is defined there. Instead, I recommend using count = Object.create(null) .

+5
source

You need to initialize your [char] counter to zero before incrementing it.

+3
source

On the first occurrence of count[char] there is undefined and undefined += 1 !== 1

+2
source

Like others, your variable is not initialized at the beginning, therefore count [char] + = 1 does not work, but when you do (count [char] || 0), you actually tell them that you want to set 0 if the variable " false ". False can mean undefined, NaN, 0.

0
source

All Articles