m90
m90

Reputation: 11822

Javascript Array logging confusion

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.sstatic.net/x2XH8.png

Upvotes: 0

Views: 857

Answers (2)

ThiefMaster
ThiefMaster

Reputation: 318638

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:

>>> var a = [1,2,3]; console.log(a.push(4)); console.log(a); console.log(a.push(5));
4
[1, 2, 3, 4]
5

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!) using a.slice(0)

Upvotes: 4

Christoph
Christoph

Reputation: 51241

Dependent of the Browser either your live array gets logged (Chrome) or A string representation (Firefox).

A shallow copy is sufficient to prevent that. Use:

console.log( a.slice(0) );

for that.

Upvotes: 1

Related Questions