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.

2
  • 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);. Commented Nov 23, 2021 at 20:42
  • @RocketHazmat Although it's surprising that there's no error for it. Commented Nov 23, 2021 at 20:44

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

"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.
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
"new String("cat") yields a string, which is a primitive value, isn't it?" no, it produces a string object, not a string primitive.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.