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.
+=operator is creating a new string and assigning it to the variable. It's as if you wrotelet a = "hello"; a = "world";— the value of the variable simply changes.originalString2declared withconstinstead oflet.a = "x"; a += "y";, underneath it you're still generating a new string and then assigning that string back toa(you're overwriting the original value of that variable with a new completely new item, rather then appending to what was already there). stackoverflow.com/a/4717855/5947043 explains it more precisely.a += bis exactly what the two symbols say: "add to, and then assign". It's rather literally the two separate operations: first the concata + b, which is kept in memory, followed by the assignment "a = the value from memory".