0

This is probably a vary noob question, but I cannot figure out what is happening. I have a simple function that I run:

function f() {
  var x = [{a:1, b: 2}, {a: 3, b: 4}];
  console.log(x);
  x.push({a: 5, b: 6});
  console.log(x);
f();

The two console.log outputs show the same thing with all three elements which I cannot understand. If I change function so that the array only contains numbers:

function f() {
  var x = [1, 2];
  console.log(x);
  x.push(3);
  console.log(x);
f();

then the outputs looks as I would have expected with the first one showing a list with items 1,2 and the second showing a list with 1,2,3.

This all runs in Firefox.

Robert
  • 725
  • 1
  • 7
  • 15
  • 1
    It's because the reference to the array is only expanded when you click on it on the console. If you use JSON.stringify, you will see its current state. Should be marked as a dupe but I couldn't find it – Ruan Mendes Jun 12 '19 at 20:27
  • 1
    I think this is related https://stackoverflow.com/questions/23392111/console-log-async-or-sync – Nenad Vracar Jun 12 '19 at 20:28
  • `console.log` is a type of I/O, and hence asynchronous. https://github.com/getify/You-Dont-Know-JS/blob/master/async%20%26%20performance/ch1.md#async-console plus the linked answers above have more in-depth explanation. – thmsdnnr Jun 12 '19 at 20:29
  • https://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays It is not related to the console being sync/async, it's just that the object is lazily evaluated when you expand it – Ruan Mendes Jun 12 '19 at 20:29

0 Answers0