title: How do I count the number of times each word appears in a string?
body: <p>I'm learning JavaScript now and I'm working on a function that will count how many times words show up in a string, then spits out the answer as an object. Per some suggestions on similar threads on this site, I've decided to use .split and a counter function to make a two-dimensional array, then populate an object with the results. I was running tests with sample texts, when I ran into some trouble with certain strings. I can't figure out why some of the counters are showing up as undefined.</p>
  
  <pre><code>function countWords(str) {
    var answer = {};
    if (str === '') {
      return answer;
    }
    var strArray = [];
    strArray = str.split(' ');
    //strArray is an array that holds the words as separate strings
    console.log('strArray: ' + strArray);
    var resultWords = [];
    var resultCount = [];
    var counter = 0;
  
    // only if the word doesnt show up in resultWords, push it in, and increase the counter. if it has shown up, disregard
    for (var i = 0; i&lt;strArray.length; i++) {
      counter = 0;
      if (resultWords.indexOf( strArray[i] ) === -1)  {
        resultWords.push(strArray[i]);
        counter += 1;
        // if the word shows up again, increase the counter
        for (var j = i + 1; j &lt; strArray.length; j++) {
          if (resultWords[i] === strArray[j]) {
            counter += 1;
          }
          // push to resultCount the counter for each word
          resultCount[i] = counter;
        }
      }
      // create an object where the key is the word from resultWords and the value is the number from wordCount
      for (var k = 0; k &lt; resultWords.length; k++) {
        answer[ resultWords[k] ] = resultCount[k];            
      }
    }
    console.log('resultWords: ' + resultWords);
    console.log('resultCount: ' + resultCount);
    return answer;
  }
  
  var sample = 'how now brown cow how now';
  console.log(sample);
  var output = countWords( sample ); 
  </code></pre>
  
  <p>I find that when I use the words "this" and "is" in my sample, I'm often returning "undefined" as the word count for those words. For example, "to be or not to be" returns "undefined" for "that" and "is." Can someone help elucidate what's going on here? Thank you.</p>