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) .
source share