0

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

b Tech
  • 412
  • 4
  • 14
  • 2
    I don't believe [`toUpperCase()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) is in place. It **returns** what you give it in upper case. – zero298 Oct 28 '16 at 13:47
  • 3
    Strings are immutable. You need to create a new string. – JJJ Oct 28 '16 at 13:47
  • 1
    Strings in JavaScript are immutable. – VLAZ Oct 28 '16 at 13:47

2 Answers2

1

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"]
Javier Rey
  • 1,539
  • 17
  • 27
-1

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

From here: How do I make the first letter of a string uppercase in JavaScript?

Community
  • 1
  • 1
mikepa88
  • 733
  • 1
  • 6
  • 20
  • Why not just mark this as a duplicate? – zero298 Oct 28 '16 at 13:49
  • 2
    If you can post the answer from another question as the answer to this question then this question is a duplicate of that other question. Flag as a duplicate instead of answering. – David Thomas Oct 28 '16 at 13:50
  • ok, but I don't see the option to flag as duplicate. – mikepa88 Oct 28 '16 at 13:54
  • It's not directly visible, if you click the flag icon below the question's tags then it brings up some options that I think include 'flag as duplicate.' – David Thomas Oct 28 '16 at 13:55
  • yeah, i did that and it shows three options "spam", "abusive" or "in need of moderator intervention" , but no duplicate – mikepa88 Oct 28 '16 at 14:00