I was helping a colleague debug some code today and I noticed a strange behavior with console.log()
in Google Chrome:
It appears that if you:
Create a nested array (e.g., [[345,"test"]])
Log the array to the console with
console.log()
.Modify one of the inner array values, then
console.log()
will output the later value -- not the values of the array at the time theconsole.log()
was executed.
JavaScript:
var test = [[2345235345,"test"]]
console.log(test);
test[0][0] = 1111111;
// outputs: [[1111111,"test"]]
var testb = {};
testb.test = "test";
console.log(testb);
testb.test = "sdfgsdfg";
// outputs: {"testb":"test"}
var testc = ["test","test2"];
console.log(testc);
testc[0] = "sdxfsdf";
// outputs: ["test","test2"]
This behavior does not happen in Firefox.
Also to note, if I stepped through his code line by line in the Chrome debugger, then console.log()
would output the correct values.
Is there an explanation for this strange phenomenon or is it just a bug with Google Chrome?
EDIT:
I've narrowed down the steps to reproduce the inconsistent console.log()
behavior:
If you add this script to your page:
var greetings=['hi','bye'];
console.log(greetings);
setTimeout(function(){
greetings.push('goodbye');
},3000);
and open it in a new window with the Chrome console window already open, then the console.log()
output will be different than if you load the page with the console window closed. Here's a JSFiddle that demonstrates that.
In the first case, with the console window already open, console.log()
will output the current value of the array (i.e., two items).
In the second case, with the console window initially closed and opened only after the page loads, console.log()
will output the later values of the array (i.e., three items).
Is this a bug in Google Chrome's console.log()
functionality?