0

Hey mods the other question you linked had nothing to do with mine. Even on that questions page it says that the behavior doesn't exist anymore.

To preface, this isn't an issue with the variable i in the closures all being the same although it might look like it is. The following code has a weird behavior. Basically the code runs the body of a for loop 3 times where it creates a set timeout that modifies and logs the same array.

const obj = {a:1,b:{c:2}};
console.log(obj);
obj.b.c = 3;

I expected when expanded the log would show that c was 2, but it actually shows that c is 3.

Why does this happen? (I already answered below)

peter duffy
  • 195
  • 9
  • do you understand that `stuff[0].a = i` runs for each iteration exactly 1 second later (all at about the same time, not one second apart) and the code updates the same value each time ... so, the result is that stuff.a === 2 (the last loop) after 1 second? – Jaromanda X Aug 03 '22 at 08:10
  • The example is overly complex. The minimal to reproduce the behaviour is `obj = {a: 1}; console.log(obj); obj.a = 2;` then expand the object in the console. You'd see it shows `{ a: 2 }`. – VLAZ Aug 03 '22 at 08:15
  • "*Even on that questions page it says that the behavior doesn't exist anymore.*" evidently it does. As you have observed yourself. Why do you say that the behaviour you yourself talk about doesn't exist? – VLAZ Aug 03 '22 at 08:21
  • 1. I'm going to modify the question to make it minimal 2. That example doesn't work. It shows proper behavior in chrome. 3. That question was about top level object properties, while this is about nested. – peter duffy Aug 03 '22 at 08:26
  • Doesn't really matter where the property is located. The thing that's logged is a live reference to the object, so when you expand it, you get the latest state of the object in any case. You're far from the first person who noticed that: [console.log() shows the changed value of a variable before the value actually changes](https://stackoverflow.com/q/11284663) | [console.log() async or sync?](https://stackoverflow.com/q/23392111) | [Weird behavior with objects & console.log](https://stackoverflow.com/q/23429203) – VLAZ Aug 03 '22 at 08:29
  • Those new links are the behavior. The 2010 one was the different top level issue. Where the unexpanded log would be incorrect. – peter duffy Aug 03 '22 at 08:44

1 Answers1

0

What is happening is that when you console.log a object only the first level of properties are stored before expanding in the console(clicking the > on an object property and seeing its properties). Think about the alternative, you deep copy every object that is logged. Then because of properties like __proto__ and constructor you would have to copy many many items. And if the object happens to have some reference to window you would practically have to take a memory snapshot.

peter duffy
  • 195
  • 9