Home >Web Front-end >JS Tutorial >Why Does Chrome's JavaScript Console Show Only the Final Value of a Modified Array?
Chrome's JavaScript Console Exhibits Unexpected Object Evaluation
In a comparison between Firefox and Chrome JavaScript consoles, a peculiar behavior emerged. While Firefox accurately prints the initial value and subsequent modification of an array, Chrome displays only the modified value for both instances.
Problem:
The following code illustrates the issue:
var s = ["hi"]; console.log(s); s[0] = "bye"; console.log(s);
Firefox's console produces the expected output:
["hi"] ["bye"]
However, Chrome's console renders:
["bye"] ["bye"]
Answer:
This behavior is due to a known and now fixed bug in Webkit: https://bugs.webkit.org/show_bug.cgi?id=35801. It involves the console's lazy evaluation of objects.
Lazy evaluation means the console does not evaluate an object until it is ready to display the output. This happens even if the object was modified before the console became active.
Solution:
To avoid this issue, one can convert the object to a string representation before logging it:
var s = ["hi"]; console.log(s.toString()); s[0] = "bye"; console.log(s.toString());
This forces the evaluation of the object immediately, and the console outputs:
hi bye
The above is the detailed content of Why Does Chrome's JavaScript Console Show Only the Final Value of a Modified Array?. For more information, please follow other related articles on the PHP Chinese website!