0

I have found that when using console.log on a nested object the result seems to print after subsequent operations have performed, but only when logging an object with a depth of at least two.

Consider the following example:

function addNumbers(data) {
    data.container.firstNumber++ 
    console.log(data); // 3
    data.container.firstNumber++
}

var numberData = {
    container : {
       "firstNumber": 1
    }
};

console.log(numberData); // 3
addNumbers(numberData);

I assumed that with this example I would see numberData printed with the values 1 and then 2. In actuality, the value is 3, 3. My first thought was perhaps there is some race condition here where the values changes before the log operation can complete, but if you add more specific references to the object, you will get the value that matches the console.log's position in the code like this:

function addNumbers(data) {
    data.container.firstNumber++ 
    console.log(data.container); // 2
    data.container.firstNumber++
}

var numberData = {
    container : {
       "firstNumber": 1
    }
};

console.log(numberData.container); // 1
addNumbers(numberData);

Why doesn't the variable evaluate to its value relative to the position of the console.log in the first example, but does in the second example?

relevant fiddle

Jonathan Lucas
  • 545
  • 1
  • 4
  • 6
  • Actually, [console.log object at current state](http://stackoverflow.com/questions/7389069/console-log-object-at-current-state) contains an invalid example. Maybe in the 4 years since then the console.log behavior has changed, but the value in console.log is only different for me when the object has to be expanded to display the value. – Jonathan Lucas Aug 06 '15 at 22:30

1 Answers1

0

Most browsers only fetch the properties of an object logged to the console when you expand the object -- and often note this in a tooltip next to the object reference.

They also tend to only expand the object the first time and cache from then on, so the console is not a reliable way to inspect objects.

To get around this, browsers offer a watch panel that will update more frequently and can be used with breakpoints or stepping to get the current state of an object repeatedly.

ssube
  • 47,010
  • 7
  • 103
  • 140