0

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.

sT331h0rs3
  • 23
  • 4

1 Answers1

2

In both cases the behaviour IS actually quite similar, if you think about it. Let's keep in mind that o.message already exists at the time you assign "set in f" to it. The new value will override the already existing value "initial value" of o.message, just as when assigning an object literal to the variable o overrides the previous value, while it already exists.

If you look at it in terms of context, the same statement is true. If o was a global variable, it can actually (to some extent) be seen as a property on the global object, which is window in the browser. So, if window.o already exists, and you do an assignment like o = {} (same as window.o = {} in this example), the behaviour is identical.

In all cases, when you are overriding an existing value of a variable or property, you're at the same time modifying the context that variable or property lives in. It's just a matter of perspective.

JJWesterkamp
  • 7,559
  • 1
  • 22
  • 28