Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is there a different output for counting each element in an array?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading