Title Case a Sentence. problem with map function

Tell us what’s happening:
Hi, here I am trying to use map to capitalize the first letter of every word in the array. Console suggests that the map function I wrote is not working. I’ve made sure that the typeof array items is string, so used string object’s method charAt, but it has not come out as I expected? Help please?

Your code so far


function titleCase(str) {
  let newStr;
  newStr = str.toLowerCase().split(" ");
  newStr.map(obj => obj.replace(obj.charAt(), obj.charAt().toUpperCase()));

console.log(newStr)
              
              //.join(" ")
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/title-case-a-sentence

.map doesn’t modify the array it’s working on. Instead it creates a new array, which you’ll have to store to another variable.

Yeah, I realized that later as well, so I changed it to forEach, but still the letters still have not been capitalized??

forEach is not ideal, because you can’t return values out of it (unlike map; forEach also always returns undefined).

Your first code is very close to a correct solution.

Ohhh, thanks for the hint, otherwise I was gonna be stuck here for probably no reasons at all!
weirdly after I applied join( which I intended to add after I have solved that map problem), I have now passed the test?. I am still confused about what went wrong though. Is it because I did not assign the mapped array to a new variable, so it cannot be logged by the console? so sometimes even if the console is not logging, the work still has been done?

Yes. That .map call did some uppercasing, but the result was not assigned somewhere and just got thrown away. What was logged was the original array, which was not modified at all by .map.

1 Like