Title Case a Sentence - Console.log different than return?

Tell us what’s happening:
HI Everyone,

I’m a bit stuck on this exercise. I’m not necessarily convinced that this is the solution - but I mainly just want to understand why things are behaving this way.

When I console.log (words[i].charAt(0).toUpperCase() + words[i].slice(1)) I’m getting a different output than if I return it, and console.log calling the function with the same argument.

Basically, what I get when I console.log (words[i].charAt(0).toUpperCase() + words[i].slice(1)) is:

[I’m A Little Tea Pot]

When I return that value, I instead get:

[I’m]

It seems like when I call the function it’s not iterating through the array… why is this the case? I appreciate any feedback you might have!

Your code so far


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

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


Your browser information:

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

Link to the challenge:

You’ve just met the early return syntax. Congrats! Yeah, it’d bite you in the backside. If you have a return inside a loop like this, you’re saying “exit the loop, and the function, and return this value as the final of the function.” Not quite what you intend.

Instead, assign those words to an array. Create another array, if you like, called capitalWords, and on each iteration of the loop set capitalWords[i] to the value you’re currently returning. Then, after the loop has finished, rejoin the capitalWords array into a sentence and return THAT.

1 Like

Ah - thank you! I figured it was something to do with the return… but thanks so much for the concise and helpful answer :slight_smile:

Got it! For those of you who are interested… final result was:

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

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