"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > `console.log` shows the reason for the modified object value exception

`console.log` shows the reason for the modified object value exception

Posted on 2025-04-15
Browse:501

Why Does `console.log` Show Unexpected Object Values After Modification?

Objects and Console.log: An Oddity Unraveled

When working with objects and console.log, you may encounter peculiar behavior. Let's unravel this mystery by analyzing this code snippet:

foo = [{id: 1},{id: 2},{id: 3},{id: 4}, {id: 5}, ];
console.log('foo1', foo, foo.length);
foo.splice(2, 1);
console.log('foo2', foo, foo.length);

In Chrome, this produces the unexpected output:

foo1 
[Object, Object, Object, Object, Object]  5
    0: Object
    1: Object
    2: Object
    3: Object
    length: 4
    __proto__: Array[0]
     5 (index):23
foo2 
[Object, Object, Object, Object]  4
    0: Object
    1: Object
    2: Object
    3: Object
    length: 4
    __proto__: Array[0]

The Asynchronous Examination

The key to understanding this behavior lies in the asynchronous nature of object examination via console.log. While the console receives a reference to the object synchronously, it does not display its properties until you expand it manually.

The Instance Variable Surprise

When you expand an object after it has been modified, you see the updated values instead of the original state. This occurs asynchronously, leading to the seemingly illogical output.

Debugging Techniques

To avoid this inconsistency, consider these debugging techniques:

  • Log individual values: Log the object's properties separately (e.g., console.log(obj.foo, obj.bar, obj.baz);)
  • JSON encode: Transform the object into a string using JSON.stringify(obj)
  • Intelligent deep copy: Use a tailored deep copy function to preserve non-serializable properties and circular references when JSON encoding (e.g., console.log(JSON.parse(JSON.stringify(obj)));)
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3