Home >Web Front-end >JS Tutorial >Why Do Chrome and Safari Console Object Display Anomalies Occur Compared to Firefox?
Object Display Anomalies in Browser Consoles
In programming, debugging involves inspecting the properties and values of objects in the console. However, users may encounter unexpected inconsistencies when displaying objects in the browser consoles of Chrome, Firefox, and Safari.
Chrome and Safari vs. Firefox: The Object Value Discrepancy
Consider the JavaScript code provided in the question:
<code class="javascript">var foo = { bar: 1111 }; console.log(foo); console.log(foo.bar); foo.bar = 2222; console.log(foo); console.log(foo.bar);</code>
While Firefox's Firebug displays the expected values as:
Object { bar=1111} 1111 Object { bar=2222} 2222
Chrome and Safari's consoles exhibit a peculiar behavior:
Object { bar=2222} 1111 Object { bar=2222} 2222
Explaining the Discrepancy
Chrome and Safari's console behavior stems from a design decision. When an object is initially passed to console.log, it is treated as a reference. Any subsequent logging of the same object will display its current value, not the value at the time of the initial log.
Once the object's tab is expanded in the console, its values become frozen and decoupled from the original object. As a result, changing the object's value afterwards will not affect its display in the expanded tab.
Workarounds
To avoid this discrepancy, developers can use methods that serialize the object into a non-object value, such as JSON stringification:
<code class="javascript">console.log(JSON.stringify(foo));</code>
The above is the detailed content of Why Do Chrome and Safari Console Object Display Anomalies Occur Compared to Firefox?. For more information, please follow other related articles on the PHP Chinese website!