Title case a sentence returning undefined and answer


function titleCase(str) {
  var startArr = str.toLowerCase().split(" "); // Makes a new array containing each word
  var newArr;// created new variable
  for (i=0; i< startArr.length; i++){
    newArr = newArr +" "+ startArr[i].charAt(0).toUpperCase() + startArr[i].slice(1);
    //Should cycle through startArr capitalizing each word and adding it to the sentence
  }
  
  return newArr;
}

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

It is returning "Undefined I’m A Little Tea Pot"
If it gets the right answer where is the undefined coming from and how can I fix it?

@noofty,
take a scenario where you are calling titleCase with an empty string. The for loop doesn’t run and newArr is undefined (since you haven’t initialized it with any value).

In your example, the same thing happens, since you have not initialized newArr with a value.

You could either just assign a new value to newArr (without adding to it) or assign it a value of an empty string.

Hope that helps.


function titleCase(str) {
  var startArr = str.toLowerCase().split(" "); // Makes a new array containing each word
  var newStr = '';// created new variable
  var final = '';
  for (i=0; i< startArr.length; i++){
    newStr = newStr + startArr[i].charAt(0).toUpperCase() + startArr[i].slice(1) +" ";
    //Should cycle through startArr capitalizing each word and adding it to the sentence
    final = newStr.slice(0, -1); // To remove the extra space on the end
  }
  
  return final;
}

titleCase("sHoRt AnD sToUt");

That got it working. Thank you for the help!