6

if objects are mutable by default why in this case it dosen't work? How to make mutation value of the key "a" in the object "s"?

var s = {
  a: "my string"
};

s.a[0] = "9"; // mutation
console.log(s.a); // doesn't work
vol7ron
  • 38,313
  • 20
  • 110
  • 168
Yellowfun
  • 398
  • 8
  • 20
  • 7
    Javscript string are immutable Check this answer. https://stackoverflow.com/questions/51185/are-javascript-strings-immutable-do-i-need-a-string-builder-in-javascript – yue you Feb 08 '18 at 19:01
  • Possible duplicate of [Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?](https://stackoverflow.com/questions/51185/are-javascript-strings-immutable-do-i-need-a-string-builder-in-javascript) – Terry Mar 24 '18 at 15:58

4 Answers4

7

You are trying to change a primitive String, which is immutable in Javascript.

For exmaple, something like below:

var myObject = new String('my value');
var myPrimitive = 'my value';

function myFunc(x) {
  x.mutation = 'my other value';
}

myFunc(myObject);
myFunc(myPrimitive);

console.log('myObject.mutation:', myObject.mutation);
console.log('myPrimitive.mutation:', myPrimitive.mutation);

Should output:

myObject.mutation: my other value
myPrimitive.mutation: undefined

But you can define a function in primitive String's prototype, like:

String.prototype.replaceAt=function(index, replacement) {
    return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}

var hello="Hello World"
hello = hello.replaceAt(2, "!!")) //should display He!!o World

Or you can just assign another value to s.a, as s.a = 'Hello World'

Top-Master
  • 5,262
  • 5
  • 23
  • 45
yue you
  • 2,008
  • 11
  • 24
3

Strings in JavaScript are immutable. This means that you cannot modify an existing string, you can only create a new string.

var test = "first string";
test = "new string"; // same variable now refers to a new string
Elliot B.
  • 16,012
  • 10
  • 75
  • 100
3

You try to mutate a string which not possible, because strings are immutable. You need an assignment of the new value.

Below a fancy style to change a letter at a given position.

var s = { a: "my string" };

s.a = Object.assign(s.a.split(''), { 0: "9" }).join('');

console.log(s.a);
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358
0

You are trying to mutate the string using element accessor, which is not possible. If you apply a 'use strict'; to your script, you'll see that it errors out:

'use strict';

var s = {
  a: "my string"
};

s.a[0] = '9';       // mutation
console.log( s.a ); // doesn't work

If you want to replace the character of the string, you'll have to use another mechanism. If you want to see that Objects are mutable, simply do s.a = '9' instead and you'll see the value of a has been changed.

'use strict';

var s = {
  a: "my string"
};

s.a = s.a.replace(/./,'9')
console.log(s.a);
vol7ron
  • 38,313
  • 20
  • 110
  • 168