4

When I perform operations on an array in javascript, console.log shows the array as having been already changed BEFORE I do an operation on the array. I can reproduce this in chrome and firefox. Anyone know why this is?

var myTabs = [[0,0,0],
              [0,0,0],
              [0,0,0],
              [0,0,0]];
console.log(myTabs);
myTabs[0].splice(1, 1);
console.log(myTabs);

See this for code:

https://jsfiddle.net/mxrh33t0/1/

YakovL
  • 7,557
  • 12
  • 62
  • 102
froopydoop
  • 85
  • 6
  • Interesting. When I try this, Chrome tells me the first array has 3 objects, but only shows 2... – a-- Jan 16 '18 at 16:14
  • Yeah, I get that too. Everything I see says that console.log is synchronous, so I don't get it. – froopydoop Jan 16 '18 at 16:15
  • @MorganLane - this is Chrome's String representation of the array at the moment it was logged, which is theoretically cheaper to store in memory than the entire object. Only when you expand the object in the console do you see the difference (due to it being the last reference to the myTabs array). – rmlan Jan 16 '18 at 16:21

1 Answers1

8

When you expand a logged object in Chrome, you are expanding the last reference to it, not a copy of that object at the moment that it was logged.

In your case, the last reference was to the array after the splice() method had been called. If you would like to verify the difference, you will have to be more specific with your logging:

var myTabs = [[0,0,0],
              [0,0,0],
              [0,0,0],
              [0,0,0]];
console.log(myTabs[0].join(","));
myTabs[0].splice(1, 1);
console.log(myTabs[0].join(","));

You can expand on that if you really want to see more.

rmlan
  • 4,387
  • 2
  • 21
  • 28
  • Thanks! Not what I expect from a logging function, really. – froopydoop Jan 16 '18 at 16:27
  • It makes sense from a resource perspective. If the Chrome devs chose to log a copy of the object every time you logged it, depending on the size of the object, that could bring the browser to its knees in a matter of seconds. In my opinion, this was a smart choice for memory management. – rmlan Jan 16 '18 at 16:38
  • Then what is a better tool for debugging? I use console.log only for debugging. – froopydoop Jan 16 '18 at 16:47
  • 2
    Try using the actual debugger (the "Sources" tab). Set breakpoints in your code and you can view the real contents in the "Scope" section of the right pane when the debugger is paused. console.log is not the best debug tool for the reason described, but it can be helpful in some cases. – rmlan Jan 16 '18 at 16:52