Title Case a Sentence problem

Tell us what’s happening:

I have no idea why it doesn’t work. It became so annoying that I tried many solutions but nothing worked as they all appeared with different errors.

Your code so far

function titleCase(str) {
  str = str.toLowerCase();
  array = str.split(" ");
  for(var i = 0; i < str.length;i++) {
  str = array[i].charAt(0).toUpperCase() + array[i].substr(1);
  return str;

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

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0.

Link to the challenge:

Any help please? I’m just about to quit fcc. I can’t take it anymore seeing myself fail at every challenge after being so close to the solution.

In your code, you’re assigning str variable to the transformation in the for loop which finally returns the value of str variable, which was set in the last iteration of the loop. You should push the transformations to an array instead.

function titleCase(str) {
    var strArr = str.split(' ');
    var arr = [];
    for (var i = 0; i < strArr.length; i++) {
        arr.push(strArr[i].charAt(0).toUpperCase() + strArr[i].substr(1));
    return arr.join(' ');

But I don’t understand. Why my previous example didn’t work?

If I read your code right. then you made an array from str words then you made an empty array.

And in the loop, you pushed the changes at the final changes to the empty array, then you joined it to have a final string.

Isn’t the same as my example? The difference is that you pushed them into an empty array while I made them directly into the variable, isn’t? So why my code didn’t work?

Also, why you made an empty array? Wouldn’t it be easier to do it directly by writing “strArr = …”?

You’re just reassigning the value of str variable in each iteration of the loop. That’s why it won’t work!

1 Like

Oh yeah. That makes a sense.

Thank you for the help!

1 Like