Title Case a Sentence (Messing around with map())

Tell us what’s happening:

I’ve already solved this challenge, but I saw that there was a possible solution using map() and replace() so I was giving this a go and I’m running into a big mess here.

I’m guessing it’s in how I’m using map(), but I’m not sure. Could anyone give me some guidance?

Thank you

Your code so far


function titleCase(str) {
 //normalize str into lowercase and split it into an array
  str = str.toLowerCase().split(" ");
  console.log(str);
  //use map() method to exert uppercase on array and replace this previous array with new one
  str = str.map().replace(str[0], str[0].toUpperCase())
  
  //console.log(str);
  //transform string array back into string
  str = str.join(" ");
  console.log(str);
  return str;
}

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/70.0.3538.102 Safari/537.36.

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

Hi.
" The map() method creates a new array with the results of calling a function for every array element.
The map() method calls the provided function once for each element in an array, in order.
Note: map() does not execute the function for array elements without values.
Note: map() does not change the original array."
W3Schools

You’re not giving the map a callback function as a parameter. Check the docs.

Your line

str.map().replace(str[0], str[0].toUpperCase());

should look something like this

str.map(word => word.replace(word[0], word[0].toUpperCase());

And I would suggest you not re-assign parameters passed to your function, this is considered best practice to the best of my knowledge. So on the first line of your function, it would be better to assign str.toLowerCase()split(' ') to a new variable called words or something like that. The reason to do this is to prevent your function from adversely effecting variables outside of its scope, which makes debugging much easier as you can treat your functions as “black boxes”.