b Tech b Tech - 1 year ago 78
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
. Why?

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


Answer Source

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"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download