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
Because
count[char] += 1
is equal to
count[char] = count[char] + 1
and the first time the code is run, count[char]
is undefined
so it's pretty much the same as
undefined + 1 // which is NaN
The working version circumvents this case by safely adding with 0
using ||
operator.
Initially, count
is an empty object†, so it doesn't have the char
property. Therefore, count[char]
returns undefined
.
And undefined + 1
produces NaN
.
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 from Object.prototype
. It would be problematic if a char
property is defined there. I recommend using count = Object.create(null)
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With