0
var a = 'cat' ;
a[0] = 'r' ;

a = 'cat'

Why..??

In case of string although you can access elements by array notation, if you try to change its content it will fail silently i.e. will not throw any error but will not change content either.

Please explain me detail.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • This is because strings are "immutable." Meaning, you can change single characters in a string. You'd have to build a new string with the pieces from `a` you want and whatever other characters. Like `var b = 'r' + a.substring(1);`. – gen_Eric Nov 23 '21 at 20:42
  • @RocketHazmat Although it's surprising that there's no error for it. – Barmar Nov 23 '21 at 20:44

2 Answers2

0

Strings are primitive values in javascript, and are therefore immutable. This is just how the language works so there's not much to explain besides that. You can read more about it here!

It is not throwing an error because you're probably not running it in strict mode.

Daniel Baldi
  • 794
  • 1
  • 9
  • "*Strings are primitive values in javascript, and are therefore immutable.*" same behaviour with `new String("cat")` - not only the primitives are immutable. Java doesn't even have primitive string, only String objects and they are also immutable. It's more of a design decision than a limitation. – VLAZ Nov 23 '21 at 20:53
  • Primitives are immutable in javascript by design. In the context of javascript this quote makes sense, though I did not specify that on my answer. `new String("cat")` yields a string, which is a primitive value, isn't it? And also my quote does not imply that non-primitive values are always mutable. But thanks for pointing that out, it is a really important distinction that I didn't consider when answering – Daniel Baldi Nov 23 '21 at 21:39
  • "*new String("cat") yields a string, which is a primitive value, isn't it?*" no, it produces a string *object*, not a string *primitive*. – VLAZ Nov 23 '21 at 21:43
0

Strings are immutable, in JavaScript only objects and arrays are mutable. You can search for mutable data types in JavaScript in Google. "A mutable object is an object whose state can be modified after it is created." MDN. You can read more here: Mutable

LHDi
  • 319
  • 1
  • 8