I'm trying to capitalise the first letter of each word in a sentence. However, the output I got from my code below is: "I'm a little teapot". I tried finding detailed explanations of how the index argument for the callback function for the map function works but found none. I want to instruct it to capitalise the letter if the element before it is a space. What's wrong with my code?
function titleCase(str) {
str= str.toLowerCase().split("");
var newArr= str.map( function(i,j){
if ( j===0 ){
return i.toUpperCase();}
else if (str[j--]===" "){
return i.toUpperCase();
}
return i;
});
return newArr.join("");
}
console.log(titleCase("i'm a little tea pot"));