Why Can't I Use Variables In Loops?

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.

In the first case, you are modifying the contents of the newObj, but in the second you are not.

currentLetter is just a variable with the contents of newObj[str[i]], not a reference to newObj[str[i]].

1 Like