Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behaviour of console.log() on Firefox 37

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?

like image 678
DrKey Avatar asked Oct 31 '22 07:10

DrKey


1 Answers

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.

like image 87
spender Avatar answered Nov 15 '22 05:11

spender