4

Let's say we have the following code

var array = [1,2,3,4];
console.log(array);
array.pop();
array.pop();
console.log(array);

Output:

[1,2]
[1,2]

Why are the 2 console.log() identical, and how come does the 1st one shows the result that was calculated after it's calling?

Is console.log() function 'delayed' somehow or by something?

PS: I'm using Sencha Touch 2.2.1 Framework, but has far has I know, they ain't overriding console.log(). I'm running this code on safari (latest version);

Fawar
  • 735
  • 2
  • 11
  • 32
  • 1
    You sure that's the code you're running? It's giving the expected output here: http://jsfiddle.net/Rttsq/ – tymeJV Aug 01 '13 at 18:20
  • I just tried it, I got `[1,2,3,4]` followed by `[1,2]` – Drew McGowen Aug 01 '13 at 18:20
  • What JS environment are you using? V8/Chrome both output `[1,2,3,4]` and `[1,2]`, as expected. – maerics Aug 01 '13 at 18:21
  • This isn't [what I'm seeing](http://jsfiddle.net/yUuZq/). Maybe there's some other javascript interfering somewhere along the way? – theftprevention Aug 01 '13 at 18:21
  • Oddly enough, when I run it in chrome with the developer pane hidden, I get two expandable `Array[2]` lines. If I run it again, they get replaced with the expected output. – Drew McGowen Aug 01 '13 at 18:25
  • 2
    possible duplicate of [Why does javascript object show different values in console in Chrome, Firefox, Safari?](http://stackoverflow.com/questions/8249136/why-does-javascript-object-show-different-values-in-console-in-chrome-firefox) – Ayman Farhat Aug 01 '13 at 18:33

2 Answers2

4

This is a well-known issue. Although the console.log calls happen in the right order, the logging mechanism itself is reference-based and can cause this a lot often in Chrome and webkit based systems. The below is a work-around which changes it from reference to value.

var array = [1,2,3,4];
console.log(JSON.stringify(array));
array.pop();
array.pop();
console.log(JSON.stringify(array));

Defect filed on the same: https://code.google.com/p/chromium/issues/detail?id=50316

Scott Mermelstein
  • 15,174
  • 4
  • 48
  • 76
v2b
  • 1,436
  • 9
  • 15
0

Which enviroment are you using? If you are in Nodejs execution is async so it can be possible. In a browser console this should not happend. In fact i tested with Chrome and FF and i get in both case

var array = [1,2,3,4];

console.log(array);

array.pop(); array.pop();

console.log(array);
[1, 2, 3, 4]
[1, 2]
undefined

Which is correct.

pm.calabrese
  • 386
  • 6
  • 10