Title Case a Sentence with forEach

Title Case a Sentence with forEach
0

#1

I have been googling and reading docs about it for a while now but I can’t understand why my forEach doesn’t work, and how I can make it work. I know I could use the map method but I’d appreciate an answer that explains how to achieve the same thing with forEach in my code.

My code

function titleCase(str) {
  var array = str.toLowerCase().split(" ");
  
  array.forEach(function(el) {
    
    el = el.replace(el.charAt(0), el.charAt(0).toUpperCase());
    
  }); 
  
  
  
  str = array.join(" ");
  return str;
}

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

Link to the challenge:


#2

The anonymous function in the forEach assigns el the capitalized version, but then you do nothing else with el.

Why not create an empty array called result before the forEach line and then push the el into result? Then, after the forEach is complete, you would thing join result back into a string and return that string.


#3

It worked, thanks!

Could you explain why my previous forEach (without the result array) doesn’t change the original array itself and make its items capitalised?


#4

Because you were not referencing the original array in your forEach. To do that, you would need to include a second argument in the function (let’s call it idx for index) and then after the el assignment line, you would do:

array.forEach(function(el,idx) {
 . 
 .
   el = el.replace(el.charAt(0), el.charAt(0).toUpperCase());
   array[idx] = el;
 .
 .
}

#5

Thanks! I had seen the index argument in docs and other resources but couldn’t implement it into my code. Now it will make more sense when I read the docs again.