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?
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?
Share Improve this question edited Mar 13, 2016 at 20:04 rene 42.5k78 gold badges121 silver badges165 bronze badges asked Feb 5, 2016 at 11:53 demonSlayerdemonSlayer 3153 gold badges6 silver badges14 bronze badges 4- check this: stackoverflow./questions/1026069/… – Gene R Commented Feb 5, 2016 at 11:55
- Can't reproduce your bug, event if it's not returning what you want – Gwendal Commented Feb 5, 2016 at 11:56
- Is there a way to fix my code? – demonSlayer Commented Feb 5, 2016 at 11:56
- @Gwendal I am running the code on freecodecamp piler so maybe thats why you aren't getting the same error message – demonSlayer Commented Feb 5, 2016 at 11:57
3 Answers
Reset to default 3Your 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);
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 es from freeCodeCamp's console, which correctly flags this as illegal, but doesn't give the correct explanation.
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");