1

I'm trying to return an object with each letter from a string as a key, and each key's value being the amount of times that letter appears.

The if statement doesn't seem to execute, I think it's a problem with the not operator because I can get it to execute if I remove it and put the letter in the object so that it evaluates to true.

function multipleLetterCount(str){    
    var countObj = {};
    for(var i = 0; i < str.length; i++){
        //Why won't this if statement run???
        if(!str[i] in countObj){
            countObj[str[i]] = 1;
        } else {
            countObj[str[i]]++; 
        }
    }
    return countObj;
}

multipleLetterCount("aaa")

It returns {a: NaN}

northjd
  • 13
  • 2
  • `!` has a higher precedence than `in`, so use parentheses to enforce the correct order. Try `if (!(str[i] in countObj))` – CRice Feb 16 '18 at 00:18

1 Answers1

4

You need to wrap your condition with the negation operator (!)

if(!(str[i] in countObj))

Or even better, invert your condition:

if (str[i] in countObj) {
    countObj[str[i]]++;
} else {
    countObj[str[i]] = 1; 
}
Ele
  • 33,468
  • 7
  • 37
  • 75