Why didn't the letters capitalize?

So I wrote:

function titleCase(str) {
  str.toLowerCase(); 
  const words = str.split(' ');
  console.log(words); 
  for (var i=0; i<words.length; i++) {
    words[i][0].toUpperCase()
  }
  console.log(words)
  return str;
}

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

The print statements I tried look the same so the for loop didn’t seem to do anything.

.toUpperCase() does not modify the input, rather it takes an input of string, and outputs the uppercase version without modifying the original.
e.g.

let lowered='cheesecake';
lowered[0].toUpperCase();
console.log(lowered); //prints cheesecake
lowered=lowered[0].toUppercase()+lowered.slice(1);
console.log(lowered); //prints Cheesecake

This is both because strings in js are immutable, and it is generally good practice to not alter inputs.

Here are readings on toUpperCase()

But didn’t you just alter the lowered string with this line?

There is an = sign, indicating that the variable is updated.

So basically with this line I’m trying to “mute” the string which is illegal in js bc strings are immutable.

lowered=lowered[0].toUppercase()+lowered.slice(1);

But with this line I am trying to update it which is legal? They seem very similar.

you can’t change a string but you can assign a new string to the same variable

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.