b Tech b Tech - 1 month ago 11
Javascript Question

Javascript: first letter of a string in array does not assigned new value. Why?

In the following code, first letter of a string in array at

index 0
does not gets replaced by the uppercase value although you can access the first letter with
arr[0][0]
. Why?

var arr = ["mangoes","orange","apple"];
arr[0][0] = arr[0][0].toUpperCase();
arr;


thanks
bt

Answer

Strings are immutable, you cannot assign a value to arr[0][0], which is a pointer within a string. You need to replace the string arr[0] with a new value:

var arr = ["mangoes", "orange", "apple"];
for (var i = 0; i < arr.length; i++) {
    arr[i] = arr[i].charAt(0).toUpperCase()+arr[i].substring(1);
}
console.log(arr); // ["Mangoes", "Orange", "Apple"]