In the function below it takes a sentence as an argument and counts the total occurrence of letters and return them as an object. The letter being the key and total number of occurrence as the value. We are starting off with an empty object. I am getting confused how the object get populated as it started empty. My confusions are commented in the code.
const wordCounter = (sentence) => {
let words = {}
// Words object is empty here
for (letter of sentence) {
// Words object is still empty here right?
if (letter in words) {
// How did the letters automatically gets stored in
// the words object when they were previously empty
// on line 3 without calling any sort of function
// to do the storing?
words[letter]++
} else {
words[letter] = 1
}
}
return words
}
console.log(wordCounter('Help me with this I am confused'))
/*Output: {
: 6
H: 1
I: 1
a: 1
c: 1
d: 1
e: 3
f: 1
h: 2
i: 2
l: 1
m: 2
n: 1
o: 1
p: 1
s: 2
t: 2
u: 1
w: 1}
*/
2
Answers
I hope i was able to make some sense of this for you.
Let’s trace the capital letter "H" – your first letter.
From this point, if we have another "H", we use the first expression to increment the value of "H" that we added during that first iteration.
Small note: "words" might be the wrong variable name to use for the object. "letters" or "lettersDictionary" might be more appropriate since you’re storing (a dictionary of) letters not words.