Monday, May 20, 2024
52
rated 0 times [  55] [ 3]  / answers: 1 / hits: 39048  / 14 Years ago, sat, october 30, 2010, 12:00:00

I’ll start with the code:


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

Simple, right? In response to this, the Firefox console says:


[ "hi" ]
[ "bye" ]

Wonderful, but Chrome’s JavaScript console (7.0.517.41 beta) says:


[ "bye" ]
[ "bye" ]

Have I done something wrong, or is Chrome’s JavaScript console being exceptionally lazy about evaluating my array?


Screenshot


More From » google-chrome

 Answers
7

Thanks for the comment, tec. I was able to find an existing unconfirmed Webkit bug that explains this issue: https://bugs.webkit.org/show_bug.cgi?id=35801 (EDIT: now fixed!)



There appears to be some debate regarding just how much of a bug it is and whether it's fixable. It does seem like bad behavior to me. It was especially troubling to me because, in Chrome at least, it occurs when the code resides in scripts that are executed immediately (before the page is loaded), even when the console is open, whenever the page is refreshed. Calling console.log when the console is not yet active only results in a reference to the object being queued, not the output the console will contain. Therefore, the array (or any object), will not be evaluated until the console is ready. It really is a case of lazy evaluation.



However, there is a simple way to avoid this in your code:



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


By calling toString, you create a representation in memory that will not be altered by following statements, which the console will read when it is ready. The console output is slightly different from passing the object directly, but it seems acceptable:



hi
bye

[#95132] Wednesday, October 27, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cadendericki

Total Points: 482
Total Questions: 109
Total Answers: 103

Location: Ecuador
Member since Thu, Jun 4, 2020
4 Years ago
cadendericki questions
Wed, Apr 7, 21, 00:00, 3 Years ago
Wed, Jul 8, 20, 00:00, 4 Years ago
Thu, May 14, 20, 00:00, 4 Years ago
;