For example we have the following JavaScript code:
function f(o) {
o.message = "set in f";
o = {
message: "new object!"
};
console.log(`inside f: o.message="${o.message}" (after assignment)`);
}
let o = {
message: 'initial value'
};
console.log(`before calling f: o.message="${o.message}"`);
f(o);
console.log(`after calling f: o.message="${o.message}"`);
In these particular lines
o = {
message: "new object!"
};
we are creating new object with name 'o', but in the previous line
o.message = "set in f";
we are modifying attribute of the original object with name 'o' (hence modifying the object itself in my understanding).
My question is why does assignment behavior differ in these situations? Shouldn't it be the same for object itself and its attributes?
For example 'o' assignment in the function body should have changed the original 'o' object instead of creating new one.