Type error: cannot assign to read only property '0' of string

Hey everyone,

I’m working on the Title Case a Sentence challenge in the Basic Algorithm Scripting section. I’m getting this error:

TypeError: cannot assign to read only property ‘0’ of string ‘i’m’

when running

function titleCase(str) {
  var newArr = str.split(' ');
  var newArrLen = newArr.length;
  for(i=0; i<newArrLen; i++){
  newArr[i] = newArr[i].toLowerCase();
    for(i=0; i<newArrLen; i++){
  newArr[i][0] = newArr[i][0].toUpperCase();
  return newArr;

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

If I remove the [0]'s from this portion:

  for(i=0; i<newArrLen; i++){
  newArr[i][0] = newArr[i][0].toUpperCase();`

the code will run and return all uppercase. Can someone please help me with the following questions?
Why doesn’t my code change just the first character of each array element?
Why does the error message call it a ‘read only property’?
If it is ‘read only’ why does it work when I have it change all characters in the array?

Thanks everyone.

1 Like

Strings are immutable, which means you can not change a part of a string once it is created. newArr[i] is a word (string), so attempting to modify a part of it with newArr[i][0] = something, is not possible.

For the same reason I mention above.

Because when you write:

 newArr[i] = newArr[i].toUpperCase();

you are now reassigning the value of the newArr element and not modifying a part of the string.