Title Case a String: getting "undefined" for variables I think I'm defining


I can’t get past an error message for this Title Case problem. The capArray variable (which I think I’m initializing and declaring correctly as a global variable) keeps throwing this error: “TypeError: capArray is undefined”. Can anyone see what I’m doing wrong here?


PS I know this is a looooong piece of code for what I’m trying to do…but I’d like to figure out this variable problem before going back and refactoring to be shorter. Thanks!

var capitalized; 
var capArray;

function titleCase(str) { 
  // Lowercase the entire string, assign to new variable
  var lowerCaseStr = str.toLowerCase();  
  // Make the string an array
  var lowerArray = lowerCaseStr.split(' ');
  // For each item in the array, replace first letter with capital letter
  for (var count = 0; count < lowerArray.length; count++) {
    // removes first word in array, assigns to temporary variable
    var lowerLetters = lowerArray.shift(); 
    // split the word into a subarray made up of letters
    var lettersArray = lowerLetters.split('');    
    // for each subarray, shift the first letter off
    // for (var count2=0; count2 < lettersArray.length; count2++){
      var toCap = lettersArray.shift();     
      // transform first letter into uppercase
      var cap = toCap.toUpperCase();
      // unshift the first letter back onto start of subarray
      // join the subarray back into a capitalized word, push into a new variable 
      capitalized = lettersArray.join('');
    // }
  // Join the capitalized words from array back into a string.
  str = capArray.join('');
  // Return the string, with all letters capitalized
  return str;

titleCase("I'm a little tea pot");