"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 > Why does Chrome's JavaScript console show unexpected results when evaluating objects?

Why does Chrome's JavaScript console show unexpected results when evaluating objects?

Posted on 2025-04-29
Browse:395

Why Does Chrome's JavaScript Console Show Unexpected Results When Evaluating Objects?

Chrome's JavaScript Console Behavior: Evaluating Objects Lazily

The behavior of the Chrome JavaScript console when evaluating objects has been observed as potentially unexpected. To illustrate this, consider the following code:

var s = ["hi"];
console.log(s);
s[0] = "bye";
console.log(s);

In Firefox, the console outputs:

[ "hi" ]
[ "bye" ]

[ "bye" ]
[ "bye" ]

Unexpected Evaluation Behavior

This behavior suggests that Chrome's console may be "lazy" when evaluating objects. When the first console.log statement is executed, the console references the object in memory. Any subsequent modifications to the object, such as changing the first element from "hi" to "bye," are not reflected in the output of the first console.log statement. This implies that the console only evaluates the object at the time of the first console.log statement and stores the snapshot.

Bug Explanation

This behavior is documented in the following Webkit bug report: https://bugs.webkit.org/show_bug.cgi?id=35801 (now fixed). The bug states that Chrome's console does not perform lazy evaluation for objects that are accessed directly, resulting in the observed behavior.

Workaround
[ "hi" ]
[ "bye" ]

To prevent this unexpected behavior, one can call toString on the object before passing it to console.log. This forces Chrome to create a representation of the object that is not altered by subsequent changes, ensuring that the console output reflects the current state of the object.

hi
bye

Output:Why Does Chrome's JavaScript Console Show Unexpected Results When Evaluating Objects?

hi bye

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