0

I've been coding for a few weeks, in this function, why are we using brackets for frequency[letter]? I originally tried doing frequency++ but that didn't work, in the tutorial the guy did frequency[] but I'm confused on why he did this. Thank you to whoever explains this to me, I know this is probably such a stupid question but I want to know why he did it so I can use it for my own code.

    const letterFrequency = (phrase) => {
        let frequency = {}
        for (const letter of phrase) {
           if (letter in frequency) {
               frequency[letter] = frequency[letter] + 1
           } else {
               frequency[letter] = 1
           }   
        }
        return frequency
    }
eateye
  • 1
  • If `letter` is `"a"`, then `frequency[letter]` is equivalent to `frequency["a"]`, which is equivalent to `frequency.a`, which is a property on the object `frequency`. `frequency++` doesn’t make sense, because `frequency` isn’t a number; `frequency.a` is. Since you don’t know which letters will exist in `phrase`, you’ll have to use bracket notation in order to dynamically access these properties. – Sebastian Simon Nov 03 '22 at 23:08

0 Answers0