Search code examples
javascriptmutablemutation

How to make mutation of a string? JavaScript


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


Solution

  • 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'