This code works:
function countAllCharacters(str) {
var newObj = {}
for (var i = 0; i < str.length; i++) {
if ( newObj[str[i]] === undefined) {
newObj[str[i]] = 1
} else {
newObj[str[i]] += 1
}
}
return newObj
}
countAllCharacters('hi')
But this doesn’t:
function countAllCharacters(str) {
var newObj = {}
for (var i = 0; i < str.length; i++) {
var currentLetter = newObj[str[i]]
if ( currentLetter === undefined) {
currentLetter = 1
} else {
currentLetter += 1
}
}
return newObj
}
countAllCharacters('hi')
These are the same thing, aren’t they? I’ve encountered this problem several times.