4

In Google Chrome the following snippet

var array = [{a: 0}];
console.log(array);
array[0].a = 1;

outputs [{a: 1}] (It doesn't when using Stackoverflow Snippet, but check it out on JsFiddle)

I suspect this is because console.log is asynchronously implemented in Chrome and the array is stored by reference. I have noticed that console.table() works fine this way.

Is there any way to make console.log() do the same?

Danyg
  • 73
  • 4
  • 1
    This is a duplicate question https://stackoverflow.com/questions/24175017/google-chrome-console-log-inconsistency-with-objects-and-arrays. Console.log is synchronous, only reference is updated. – Shyam Babu May 08 '18 at 08:58
  • @ShyamBabu If it was synchronous (as in it blocks execution until it is finished) wouldn't `console.log()` output the initial value before proceeding and changing the reference on the next line? – Danyg May 08 '18 at 09:25
  • No this is not a matter of the console.log being async or sync. This is chrome updating the UI value after the initial conosole.log when you tried previewing.If you try this in node REPL you will not get this behaviour. – Shyam Babu May 08 '18 at 10:51

2 Answers2

1

You want to log a copy of the object, this is especially useful when you can't control when the arrow in the console will be clicked.

If the object contains JSON friendly types console.log(JSON.parse(JSON.stringify(a)) will work.

How to Deep clone in javascript will help with more complicated objects.

Crazometer
  • 457
  • 7
  • 12
  • This won't work if the object contains circular references – Danyg May 08 '18 at 08:50
  • That can get kind of complicated and it's normally easier to use a third party library like https://lodash.com/docs/4.17.10#cloneDeep. See the link in the post. – Crazometer May 08 '18 at 08:56
0

Console log holds a reference to an object, it doesn't clone it just to print it to console. That would be ridiculous. If you want to remember the state you either need to JSON.stringify the object, or deep clone it manually.

Edit: It is synchronous. The UI redraws when you refresh the view. I mean e.g. if you click on triangle.

enter image description here

deathangel908
  • 8,601
  • 8
  • 47
  • 81
  • True, but if `console.log` was synchronously implemented it wouldn't matter that it outputs a reference. Also this won't work with objects that has circular references – Danyg May 08 '18 at 08:49
  • 1
    "That would be ridiculous" a few months (years?) ago, the *i* icon offered an option to show the value as it was at the time it was logged. Not that much ridiculous. – Kaiido May 08 '18 at 09:02
  • It showed its value because UI simply didn't update. – deathangel908 May 08 '18 at 09:15