Title Case a Sentence -- returns string but fails all tests

Tell us what’s happening:

My code returns a string with each word capitalized, however all the tests fail. I do not see an extra space anywhere.
What might be going on here?
Thank you!

Your code so far


let result = [];
function titleCase(str) {
  str = str.split(' ');
  for (let i = 0; i < str.length; i++){
    result.push(str[i].charAt(0).toUpperCase() + str[i].slice(1).toLowerCase());
  }
  result = result.join(" ");
  return result;
}

titleCase("sHoRt AnD sToUt");
console.log(result);
console.log(typeof result);


Your browser information:

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

Challenge: Title Case a Sentence

Link to the challenge:

Hi and welcome to the forum.

The problem is that you are using a global variable that gets modified each time your function is run. Moving your result variable inside of your function will fix your problem.

2 Likes

Thank you Jeremy,
That did fix it!
I need to read more about scope…

1 Like