Title Case a Sentence challenge. I know this is ugly but why doesn't it work?

It’s horribly inefficient but I don’t understand why it doesn’t pass the challenge.

So where does the for loop actually close? What happens if you console.log(result) just before you return it?

You likely don’t want to join the array inside the for loop, and with the return inside the loop, it only happens the first time.

You’ve discovered the Early Return Pattern! :partying_face:

Thanks for the reply! If I console.log the result just before the result, I get the desired result as far as I understand. I tried the examples that need to pass in the challenge.

I also tried it with the IF statement deleted, with return array.join(’ '); outside of the FOR statement, and it still seemingly works with the examples I’ve tried.

Does the for loop not stop after it reaches the length of the array of the individual words? And then it would join them all with the correct spacing after the last iteration.

My bad, I missed the if(i===splitWords.length-1) bit. Which you don’t really need, as the loop is ending when i is splitWords.length. But anyway.

I am truly sorry, I provided you with a false lead. So each time through the loop, you are pushing the first letter capitalized, the rest of the word lowercase, and a space. Then, when you have the full string processed, you are joining the entire array into a string, yes?

So what about that extra space at the end? You aren’t returning "Short And Stout", you’re returning "Short And Stout " (notice the space at the end of that last one).

To see what I mean, add this after your function:

const string = `sHOrT aNd STOUT`;
const updatedString = titleCase(string)

console.log(string+" is "+string.length+"  characters long.");
console.log(updatedString+" is "+updatedString.length+"  characters long.");

That will show you the before-and-after of your function. Or here it is on https://replit.com/@TobiasParent/titleCaseAString, a handy “sandbox” site:

1 Like

I forgot about the space after the last word… I couldn’t see it in the console. Thanks for clearing that up!

I abandoned my code and now I’m trying to wrap my head around the map() method. I’ll give that sandbox site a try. Thanks so much for your help.

1 Like

Because you can’t see it, it’s easy to forget. I didn’t even think about it the first go-round - but comparing the string going in and the string coming out was the trick.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.