I'm trying to wrap my head around the code structure of a solution I stumbled upon.
The issue at hand: Create a function that takes in a string with only lowercase letters as a parameter, and returns an object with each letter and the number of times it appears in the string.
The proposed solution:
function analyzeFrequencies(string) {
const frequenciesObj = {};
for (let i of string) {
frequenciesObj[i] = frequenciesObj[i] + 1 || 1;
}
return frequenciesObj;
}
I get the first line where the function is defined with a parameter.
The second line makes sense, an empty object being initialized.
Line three involves a for loop iterating through a variable based on its indices. Got it.
However, line four is puzzling to me. It seems like frequenciesObj[i] =
is assigning a value to a key within the object. = frequenciesObj[i]
is initiallly undefined? + 1 || 1
- adding one or setting one?
How does it determine whether to set or add a value? How can a letter from the string become a key in the object?