I’m trying to personally understand why the following code behaves as it does. Specifically, why does the first console.log(...)
expression output the full-and-final version of someObject
?
var someObject = {}; // OUTPUT: console.log(someObject); // {prop: {key: "differentValue"}} <-- WHY!? console.log(someObject.prop); // undefined someObject.prop = {key:"value"}; console.log(someObject); // {prop: {key: "differentValue"}} <-- WHY!? console.log(someObject.prop); // {key: "value"} someObject.prop = {key:"differentValue"}; console.log(someObject); // {prop: {key: "differentValue"}} console.log(someObject.prop); // {key: "differentValue"}
I ran across this while coding something for myself wherein I wanted to see the state of an object at each iteration through a for-loop. I was surprised to see that the object output to the console was the same at each turn; that state being the end-state of the object after the whole loop had executed.
What’s even more confusing to me, and the part I really would like to understand, is why the reading of the properties of the object do seem to work as one (or at least I) would expect.
I thought maybe this question or this question might’ve helped explain, but I think they’re not quite related.