Title case a sentence returning undefined and answer

Title case a sentence returning undefined and answer
0

#1

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?


#2

@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.


#3

You declared newArr, but did not assign it a value. All declared but unassigned variables get the value undefined by default. Since ultimately newArr should be a string at the very end of the return, think about what value to assign to newArr in the above line.

Since you know newArr is going to be a string, you might want to consider naming it something like newString instead of newArr. It makes your code more readable. When I see newArr, I assume you are going to be creating/using an array.


#4

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!