Upon debugging JavaScript objects in different browsers, developers may encounter discrepancies in the displayed values in the console. This article explores this issue, providing an explanation for the observed behavior.
Consider the following JavaScript code:
var foo = {bar: 1111}; console.log(foo); console.log(foo.bar); foo.bar = 2222; console.log(foo); console.log(foo.bar);
In Firefox, the expected output is observed:
Object { bar=1111} 1111 Object { bar=2222} 2222
However, in Chrome and Safari, the output differs:
Object { bar=2222} 1111 Object { bar=2222} 2222
This difference arises from a design decision in Chrome's (and, by extension, Safari's) browser console. When logging an object, Chrome creates a reference to the object itself. Upon clicking and opening the object tab in the console, the logged value remains constant, regardless of any subsequent changes to the object. This creates a discrepancy between the displayed value and the actual value of the object in memory.
To resolve this issue and obtain the expected output in Chrome and Safari, developers can employ any method to serialize the object, such as JSON.stringify():
console.log(JSON.stringify(foo));
This will display the object's JSON representation, ensuring a consistent output across all browsers.
The above is the detailed content of Why do Chrome and Safari display different object values in the console compared to Firefox?. For more information, please follow other related articles on the PHP Chinese website!