18

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

I have the following snippets in javascript whose output makes me feel that something is going wrong.

1.

a=2;
console.log(a);
a+=2;
console.log(a);

Output:2 4 ; as expected

2.

t=[0,2];
console.log(t);
t[0]+=2;
console.log(t);

Output: [2,2] [2,2]

Shouldn't the output be [0,2] [2,2] ? And whats the difference between the above two cases that results in the different answers in both the cases?

Community
  • 1
  • 1
gopi1410
  • 6,567
  • 9
  • 41
  • 75

4 Answers4

18

It's because the log is delayed until Chrome has time to do it (i.e. your scripts releases the CPU).

Try this to understand what happens :

var t=[0,2];
console.log(t);
setTimeout(function() {
     t[0]+=2;
   console.log(t);
}, 1000);

It outputs what you expect.

Is that a bug of Chrome ? Maybe a side effect of an optimization. At least it's a dangerous design...

Why is there a difference ? I suppose Chrome stores temporarily what it must log, as a primary (immutable) value in the first case, as a pointer to the array in the last case.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
8

console.log in chrome/ff is asynchronous and objects that are logged are interpreted at the time when they're expanded. . Instead make a copy of the object if you want to see its value at that time (for an array):

t=[0,2];
console.log(t.slice(0));
t[0]+=2;
console.log(t);

With an array, calling .slice will duplicate the array and not create a reference. I wouldn't suggest using a time out: this really doesn't solve the problem, just circumvents it temporarily.

zamnuts
  • 9,492
  • 3
  • 39
  • 46
0

Everything you're doing is right, but chrome's logging is screwy/delayed. Try making a copy of the variable and adding to that and you'll see that your code is correct.

Lusitanian
  • 11,012
  • 1
  • 41
  • 38
0

Chrome's logging is delayed in the newer versions, no problem from your end. Make a copy of the variable or use setTimeout.