Chrome's JavaScript Console Evaluation Behavior for Objects
In the given code snippet:
var s = ["hi"]; console.log(s); s[0] = "bye"; console.log(s);
Firefox and Chrome consoles display different results. Firefox shows the updated array after the modification, while Chrome displays the modified value in both instances.
Cause of the Discrepancy
Chrome's JavaScript console performs lazy evaluation for objects. This means that it only evaluates the object when it is necessary, such as when it needs to display it in the console. Therefore, in this case, Chrome is not evaluating the object during the first console.log statement but instead waiting until the second console.log statement is executed. This allows Chrome to avoid the overhead of evaluating the object prematurely.
Avoiding Laziness
To force Chrome to evaluate the object immediately, one can use the toString method of the object, like so:
console.log(s.toString());
By calling toString, a representation of the object is created that will not be altered by subsequent statements. When Chrome evaluates the console.log statement, it will have the updated value of the object on hand, so no lazy evaluation will take place.
The above is the detailed content of Why Does Chrome's JavaScript Console Show Different Object Evaluation Behavior Than Firefox?. For more information, please follow other related articles on the PHP Chinese website!