In the code below if count[item] is truthy increment it else set it’s initial value to 1
however I don’t understand why when I give the property a string value other than 0 (of course) the final result is a:2
const letters = ["a", "b", "a", "b", "c", "d", "a"];
let count = {"a": 0}; // 0 or "0"
letters.forEach(function (item){
if (count[item]){
count[item]++
}else {
count[item] = 1
}
})
console.log(count)
// result
a: 3
b: 2
c: 1
d: 1
now the result here is different
let count = {"a": "asdasd"}; // or any other string
letters.forEach(function (item){
if (count[item]){
count[item]++
}else {
count[item] = 1
}
})
// result
a: 2
b: 2
c: 1
d: 1
Can please someone explain?
>Solution :
When you insert an arbitrary string in there, you end up doing this:
count["asdasd"]++
This will result in:
{a: NaN}
Because you can’t increment a string. The next time the letter a is encountered in letters though, the if checks the following:
if (count['a']) { // if (NaN) {
Since NaN is falsey, that check is false, and the NaN is overwritten by 1 due to count['a'] = 1. That means the first increment was lost, so the final count is one less than it should be.