5

Some minutes ago, while playing with javascript, I noticed a strange behaviour of console.log(). In fact it seems to log "distorted" variables. Take a look to the following:

var res = document.getElementById("res");
var arr = ["1", "2", "3"];
arr.push("4");
res.innerHTML = JSON.stringify(arr)+'<br>';
console.log(arr);
arr.push("5");
res.innerHTML += JSON.stringify(arr);
console.log(arr);
<div id="res"></div>

It prints correct variables into #res but not into browser console (Firefox 37)

enter image description here

Could someone explain me why this happens?

DrKey
  • 3,365
  • 2
  • 29
  • 46

1 Answers1

2

So, if you change your logging so that you're taking a copy of the array:

var arr = ["1", "2", "3"];
arr.push("4");
console.log(arr.slice());
arr.push("5");
console.log(arr.slice());

Everything works as expected.

I'm discounting "live" tracking as a possibility, because the following example does not display any evidence of live tracking:

var arr = ["1", "2", "3"];
console.log(arr);
var i;
i = setInterval(function(){
  arr.push(1);
  console.log(arr);
  if(arr.length>10)clearInterval(i)
},1000);

This implies that the logging is queued and the queue does not run until after the last push to the array (probably until your javascript has finished executing).

Nice find... definitely something that might catch out developers.

spender
  • 117,338
  • 33
  • 229
  • 351
  • Yes, I have noticed similar behavior some time ago in Chrome, I am not very sure how logging works but it might be event based. In this case, there might be some kind of race condition somewhere. – Octav Zlatior Apr 09 '15 at 11:07