3

Everything I'm reading about modifying strings in Javascript says that strings are immutable. Hence why concat returns a new string that is a modification of the original:

let originalString = 'hello';
let modifiedString = originalString.concat(' world');
console.log('originalString:', originalString);
console.log('modifiedString:', modifiedString);

results in:

"originalString: hello"

"modifiedString: hello world"

So far it makes sense. The original string remains even after concat because strings are immutable.

However, if I do the following:

let originalString2 = 'hello';
let modifiedString2 = originalString2 += ' world';
console.log('originalString2:', originalString2);
console.log('modifiedString2:', modifiedString2)

the result is:

"originalString2: hello world"

"modifiedString2: hello world"

This sure seems like it's mutating the original string to me. If that is not what's happening, can someone explain it to me? I've even found articles that go over the ways to modify strings that say at the beginning "Javascript strings are immutable" and later go on to say that the += method is mutating the original string, so I'm getting contradictory information.

JSFiddle of the simple test

Case Silva
  • 466
  • 7
  • 26
  • 3
    The `+=` operator is creating a **new** string and assigning it to the variable. It's as if you wrote `let a = "hello"; a = "world";` — the value of the variable simply changes. – Pointy Oct 12 '21 at 14:29
  • There's a difference between changing a string (you can't), and changing a variable's value. Try your code test with `originalString2` declared with `const` instead of `let`. – Pointy Oct 12 '21 at 14:30
  • 1
    They're immutable because you can't modify them in-place. That doesn't mean you can't generate a new string by joining two others together - which is what += does. Even if you write `a = "x"; a += "y";`, underneath it you're still generating a new string and then assigning that string back to `a` (you're overwriting the original value of that variable with a new completely new item, rather then appending to what was already there). https://stackoverflow.com/a/4717855/5947043 explains it more precisely. – ADyson Oct 12 '21 at 14:30

1 Answers1

3

I think it's because of the short hand addition operator (+=) you're using. It's actually doing 2 operations first addition then assignment.

let x = 2;
x += 2;
// The above line is equivalent to the following.
x = x + 2;

So for you're example

let str = "hello";
str += "world"; // is the same as 
str = str + "world";

So we are making a new string by str + "world" then assigning it to our str variable. So it's still immutable :)

h-sifat
  • 1,455
  • 3
  • 19
  • 1
    Ok, this makes sense to me. The string itself is not being mutated, the variable is just being reassigned with a shorthand operator. Thanks for that explanation! – Case Silva Oct 12 '21 at 15:05