demonSlayer
demonSlayer

Reputation: 315

can't understand why code is giving error: TypeError: 0 is read-only

I have just started learning JavaScript and was attempting bonfire questions in freecodecamp. My code is meant to make the first letter of each word capital. Code:

function titleCase(str) {
  str = str.toLowerCase ();
  var arr = str.split(' ');

  for(var i=0; i<arr.length; ++i) {
    arr[i][0] = arr[i][0].toUpperCase();           
  }

   str = arr.join (' ');
   return str;
  //return arr[0][0];
}

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

Instead its returning an error:
TypeError: 0 is read-only

I would have understood the error had I been trying the operation on a string (them being immutable). But I am trying to edit an array which is perfectly mutable.

What is wrong with my code?

Upvotes: 1

Views: 12764

Answers (3)

lgimberis
lgimberis

Reputation: 35

arr is indeed an array. Its elements are mutable, so you can replace arr[i] with another string.

However, arr[i] is a string. Trying to assign to arr[i][0] is not valid because you're trying to modify an immutable string.

The error comes from freeCodeCamp's console, which correctly flags this as illegal, but doesn't give the correct explanation.

Upvotes: 3

Vadivel S
Vadivel S

Reputation: 660

You change Your Javascript like this

function titleCase(str) {
str = str.toLowerCase ();
var arr = str.split(' ');
for(var i=0; i<arr.length; ++i) {
 arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].substring(1);   
}


str = arr.join (' ');
 return str;
//return arr[0][0];
}

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

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68393

Your code is not giving any error, but it is not making the first character uppercase either

replace this line

arr[i][0] = arr[i][0].toUpperCase(); 

by

arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].substring(1);

Upvotes: 3

Related Questions