Title Case a Sentence - Code not accepted

Title Case a Sentence - Code not accepted
0.0 0

#1

Hi there! I seem to have a problem with my code not being accepted. It seems to be working fine in terms of getting the required output, but it doesn’t seem to be passing the challenge on freeCodeCamp. I’ve added .trim() to my return output to clear out any whitespace but the issue still persists. Any help would be greatly appreciated!

var strArr = []; // multiple strings in an array
var numberOfStr = 0; // corresponds to number of strings in strArr
var n = 0; // index for individual substrings

function titleCase(str) {
// var substring is the result of converting str to lowercase and splitting it)
  for (var substring = str.toLowerCase().split(' '); n < substring.length; n++) {
    // substringCase converts the first index of a substring into uppercase
    var substringCase = substring[n][0].toUpperCase().concat(substring[n].slice(1));
    // makes sure that amount of strings in new array === amount in old array
    if (numberOfStr < substring.length) {
      numberOfStr = strArr.push(substringCase);
    }
  }
  return strArr.join(" ").trim();
}


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

#2

In the above line, you refer to a variable named strArr, but you have not defined such a variable anywhere in your code. That is why you get the error ReferenceError: strArr is not defined


#3

Oops, accidentally left out the first row var strArr = []; in the forum editor. Thanks for pointing that out. However, the code still seems to work fine but it has yet to be accepted by freeCodeCamp


#4

If by first row, you mean outside the function, then strArr will keep the value it had after each test is ran by the FCC tests. This is a perfect example of why you should avoid global variables when you can. Move strArr inside and see what happens.


#5

Sweet, problem solved! Thanks Randell! :slight_smile: