I am trying to get the count of the most repeated letter in a 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
On first occurrence
count[char]
is undefined andundefined += 1 !== 1
Initially,
count
is an empty object†, so it doesn't have thechar
property. Therefore,count[char]
returnsundefined
.And
undefined + 1
producesNaN
.Therefore, you must inititialize it to
0
in order to make it work properly.†:
count
is not really an empty object because it inherits properties fromObject.prototype
. It would be problematic if achar
property is defined there. I recommend usingcount = Object.create(null)
instead.You need to initialize your count[char] to zero before incrementing it.
Because
is equal to
and the first time the code is run,
count[char]
isundefined
so it's pretty much the same asThe working version circumvents this case by safely adding with
0
using||
operator.As other said your variable is not initialize in the beginning so count[char] +=1 is not working, but when you do (count[char] || 0) you actually tell them that you want to set 0 if the variable is "false". False could mean undefined, NaN, 0.