I'm trying to 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
? I realize it has something to do with hoisting (maybe?) or some other concept I don't fully grasp. Just searching this on the web was challenging, as I don't have the lexicon to properly search what I want to know.
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 discovered 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 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, while at the same moment, the whole object itself appears to have different values.
I thought maybe this question or this question might've helped explain, but I think they're not quite related.