Title Case a Sentence (cannot read property '0' of undefined)

Hey everybody,

I know that this is certainly not the most efficient solution for this, but I am a beginner and am struggling through it. Right now I have it where all of the words that are passed through the function are title cased. However, whenever I try to return (or even console.log) titleCaseArray, I get "cannot read property β€œ0” of undefined. Anybody know why that is?


Your code so far

function titleCase(str) {
  var arrayOfStrings = str.toLowerCase().split(" ");
  var titleCaseArray = [];
  for (i = 0; i <= str.length; i++) {
    var firstLetter = arrayOfStrings[i][0];
    var restOfWord = arrayOfStrings[i].slice(1, arrayOfStrings[i].length);
    var bigCase = firstLetter.toUpperCase() + restOfWord;

  return titleCaseArray;

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

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.73 Safari/537.36.

Link to the challenge:

That’s caused from the inconsistency of the looping for for the string length and looking at a different array.

Let’s take I'm a little tea pot as string input for example:

arrayOfString.length // 5
str.length // 20

So when looping you are going all the way up to 20, yet the indexes of arrayOfString stop at 5 resulting in undefined when trying to access the values:

 for (i = 0; i <= str.length; i++)

arrayOfString[6] // undefined
arrayOfString[7] // undefined
// and so on

Make sense? :+1:

1 Like