I am declaring a function that, when given a string as an argument, returns an object where keys are the words in the string. Values are the # of occurrences of that word in the string.
When I run the below code, I get {}.
function countWords(string) {
var result = {};
var words = string.split(' ');
for (var i = 0; i < words.length; i++) {
var currentElement = words[i];
var prop = result[currentElement];
if(prop) {
prop += 1;
} else {
prop = 1;
}
}
return result;
}
console.log(countWords('hello hello')); // => {'hello': 2}
However, replacing prop = 1
with result[CurrentElement] = 1
returns the expected answer.
Why is it wrong to use prop = 1 in this context?