You are comparison is wrong. You are performing very different operations. In your object example you do
obj.c = 3
You are reading from obj
and mutate the object. You are not creating a new object.
In your string example you do
str += 'aoeu'
Here you are writing to str
, overriding its previous value with a new string value. That's a completely different operation than what you do with the object.
If you were doing the same operation with the object, you would get a similar result. The equivalent example would rather be something like
obj = {a: obj.a, b: obj.b, c: 4};
Assigning a new value to variable, never updates the value of another variable:
var foo = 42;
var bar = foo;
foo = 21;
bar
will stay 21
. It doesn't matter which value foo
had at the beginning (number, string, object, ...).
However, there are two aspects of objects that are important to understand: Objects are
- mutable
- represented as reference
That means if you have an object and assign it to another variable:
var foo = {};
var bar = foo;
foo
and bar
now point to the same object in memory. Because objects are mutable, they can be changed "in place":
bar.x = 5;
console.log(foo.x);
Primitive values (anything that is not an object), are immutable. They cannot be changed in place:
var foo = "abc";
foo[0] = "x";
console.log(foo); // still "abc", not "xbc"
Because of immutability, "changing" a value implies creating a new value. That new value has to be "put" somewhere, which is often done be assigning it to the same variable:
foo = 'x' + foo.substring(1);
Or put in other words: Immutable values force us to assign new values to variables.