0

I am logging some objects in the browser console, and here are the results:

enter image description here

On surface-level, the result looks correct. Although, when I unfold and inspect the object further, their values are totally incorrect. Blue circles are the expected info, then the red lines show something different. They all have the same value as the last object value (including purchaseDate).

The simplified javascript code that I am executing:

let res = []
for (const obj of objects) {
    console.log(obj)
    res.push(obj)
}

Am I missing something?

Burger Bob
  • 131
  • 3
  • Sounds like the array of objects is being constructed wrong - they're all the same object, rather than separate objects – CertainPerformance Oct 22 '22 at 16:28
  • Because you have one variable in the for condition: obj. This variable references the actual object. But as the condition run, it keeps changing. So firstly chrome logging it with the current data, but if you unfold it, then you see the obj's variable's last value, which is the last object in the list. So the correct way to print reference type is this: console.log(JSON.stringify(obj)) – Jung Ervin Oct 22 '22 at 18:11

0 Answers0