0

It must be super simple, but I'm completely stuck.

var arr = ["ABCD", "asda12"];
var a = arr[0];
a[1] = 'S';
console.log(a[1]);

It logs "B" and I expect "S", why can't I do it this way?

frudee
  • 1
  • 1
  • Strings are immutable, you cannot change them this way. The array access is for convenience, you cannot treat them the same way as arrays. – VLAZ Oct 14 '20 at 16:25

1 Answers1

0

In your code, "a" is a string and you can't change it's value in that way. You can try setting "a" as an array, then you can change it with the way you do:

var arr = ["ABCD", "asda12"];
var a = [...arr[0]];
a[1] = 'S';
console.log(a[1]);
sibumi
  • 81
  • 4
  • It works, but it splits "ABCD" into 4 strings in an array, which isnt very helpful, as I want to get 1 string: "ASCD" – frudee Oct 14 '20 at 16:33