5

I don't understand why console.log displays that d1 contains [100,200,300] before I even introduced these numbers. Regular for loop displays internals of d1 correctly though. Can someone please explain this behavior/bug of console.log in Google Chrome? https://jsfiddle.net/ZSvyt/

var container = {};
container["0"] = [10, 20, 30];
var d1 = container;

console.log('before console.log');
console.log(d1); // <--- IT DISPLAYS [100, 200, 300]. WHY?

// before for loop
console.log('before for loop');
for (var i = 0; i < d1["0"].length; i++) {
    console.log(d1["0"][i]);
}

container["0"] = [100, 200, 300];

console.log('after console.log');
console.log(d1);

// after for loop
console.log('after for loop');
for (var i = 0; i < d1["0"].length; i++) {
    console.log(d1["0"][i]);
}

Output:

before console.log
Object {
    0: Array[3]
}
0: Array[3] 
0: 100
1: 200
2: 300 

before for loop
10
20
30

after console.log
Object {
    0: Array[3]
}
0: Array[3] 
0: 100
1: 200
2: 300

after for loop
100
200
300
yaru
  • 1,260
  • 1
  • 13
  • 29
  • 1
    This will sometimes happen with nested _Objects_ because the console's lookup can happen after the reference has been changed. If it's important it's exact, use _JSON_ – Paul S. May 10 '15 at 10:52
  • this screwed me up so hard.. at least now I know – Kareem Kamal Feb 26 '19 at 17:30

1 Answers1

9

that's because what is in the console is the reference of dt not a copy.

you can copy the object and log it (the code from this question ).

or you can log the string that represents it using JSON.stringify.

console.log( JSON.stringify(dt) ); will print it as string.

Also if you are using lodash then you can use console.log(_.cloneDeep(dt)) to clone and log the correct values inside the object at that very moment.

Rahul Gupta
  • 9,775
  • 7
  • 56
  • 69
Omar Elawady
  • 3,300
  • 1
  • 13
  • 17