I have noticed something that I cannot understand at all. I am doing something really simple in JavaScript:
var a = [1,2,3];
console.log(a.push(4));
console.log(a);
console.log(a.push(5));
I would expect the console to log: 4, [1,2,3,4], and 5 as described here for example.
The catch is that the actual console output looks like: 4, [1,2,3,4,5], and 5
See: http://jsfiddle.net/HknMF/
What on earth makes the 5 appear in the second log output?
EDIT: fwiw here’s a screenshot of Firebug showing both behaviors: https://i.stack.imgur.com/x2XH8.png
The console in some browsers uses a reference to the array/object, so when you inspect it and the object changed after the
console.log()call you’ll see the changed object.In Firefox this also happens for objects, but not for arrays which are displayed inline anyway:
Especially for objects that do not contain functions a quick workaround is either cloning them (log
$.extend({}, yourObject)if you have jQuery) or logging their JSON string version (then you lose the nice object view and just get a plain string though). An array can easily cloned (shallow copy!) usinga.slice(0)