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)
Could someone explain me why this happens?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With