I'm doing a class on javascript this semester, and one of this week's exercises was to take a string of words, and capitalize the first letter of each word.
I did that using .map()
, the code is here :
let t1 = "hello how are you doing".split(" ");
let t2 = t1.map(function(word) {
return word[0].toUpperCase() + word.slice(1);
});
console.log(t2.join(" "));
And it works perfectly fine. However, I was wondering why, when I try with forEach()
, I can't make it work. Here is my code :
let t1 = "hello how are you doing".split(" ");
t1.forEach(function(word) {
word[0] = word[0].toUpperCase();
})
console.log(t1.join(" "));
My understanding of forEach()
is that it cycles through every element of the table, much like a simple for loop. So then shouldn't my code take the first letter of each word, and replace it with the same letter, to which toUpperCase()
is applied?
edit : I already know how to capitalize the first letter of each word, I was just asking about the different methods