Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bug in console.log? [duplicate]

Possible Duplicate:
Is Chrome's JavaScript console lazy about evaluating arrays?

I try the following code:

var myList = new Object();
var item   = new Object();
item.text  = "item-1";
myList[3]  = item;

console.log(myList);
console.log(myList[3].text);

// Assign another object to the same entry
var item2   = new Object();
item2.text  = "item-2";
myList[3]  = item2;

console.log(myList);
console.log(myList[3].text);

The result is quite odd:

* Object
  * 3: Object
      text: "item-2"

item-1

* Object
  * 3: Object
      text: "item-2"

item-2

BUT - if i execute the second part after some time (using setTimeout), and unfold the first object, I get it right, i.e.:

* Object
  * 3: Object
      text: "item-1"

item-1

* Object
  * 3: Object
      text: "item-2"

item-2

I find it important to share it, since I think one can waste a lot of time trying to understand what's wrong in his code. And if somebody has some reference to an open bug or something - please reply this ticket. Thanks!

like image 316
guyaloni Avatar asked Jun 20 '12 11:06

guyaloni


2 Answers

My view is that this is a horrendously irritating 'feature' that I really wish I could turn off, it makes debugging a nightmare, not knowing at which point in time something may have updated an object, whilst trying to establish exact object state at a give point in the code. The feature could be useful for 'watch points' etc, but not in something called a 'LOG' (the clue is in the name).

Consider this code fragment:

var person = {'name':'Tom'};
console.log( person);  //output the entire object variable
person.name = 'Thomas';
//the output is an object, whose 'name' value is 'Thomas', even though the log statement was placed before the value was changed to 'Thomas'.

AND THEN:

var person = {'name':'Tom'};
console.log( person.name);    //changed to output a string variable
person.name = 'Thomas';
//the output here, however, has not dynamically updated and correctly outputs 'Tom'
like image 196
Tom Carnell Avatar answered Sep 29 '22 22:09

Tom Carnell


this is a known bug (50316) that gets reported again and again because people don't take a look at the bugtracker before reporting:

  • 78325
  • 94887
  • 105559
  • 107828
  • 111020
  • 131124

sadly, theres no information about if/when this will get solved. until that moment, you'll need to clone objects before passing them to console.log().

like image 31
oezi Avatar answered Sep 30 '22 00:09

oezi