0

I have following simple javascript code:

s="hello"
s[0]="X"
console.log(s[0])

The output is h, but I have updated it as X, I would ask why I got such result, thanks.

Tom
  • 5,848
  • 12
  • 44
  • 104
  • 2
    Strings are immutable, you can't edit them you can create a new like `s = "X" + s.substring(1)` – nick zoum Jun 03 '21 at 01:39
  • Add `'use strict';` at the top of your script and you'll see the error (and likely more, over time). Also `console.print` isn't function, but I assume you mean `console.log`. – msbit Jun 03 '21 at 01:40

1 Answers1

2

Strings in JavaScript are primitives, which means they are immutable, ie. you are not able to change them. If you were running your code in strict mode then this would throw an error.

If you wanted to modify this string you would need to effectively create a copy of it, and then assign that to the s variable eg.

s = "X" + s.substring(1)
MattieTK
  • 501
  • 6
  • 15