0

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

6
  • 1
    are you sure? I tried running your code in jsfiddle and the console output is as expected... I am on Firefox 10.0.2. What browser are you using? Commented Mar 16, 2012 at 9:14
  • @Hery yes I am sure, I tried it in Chrome & Firefox (with Firebug). What kind of console are you using? Firebug too? Commented Mar 16, 2012 at 9:18
  • @Hery strangely enough I can get Firebug to show both behaviors. The "odd" one will display a HknMF/show as source, the other one states _display Commented Mar 16, 2012 at 9:22
  • Very weird indeed. For me, both HknMF/show and _display show the same output. I tried running the jsfiddle code in chromium though, and I finally get to see your output... Commented Mar 16, 2012 at 9:25
  • @Hery I added a screenshot, very weird.... Commented Mar 16, 2012 at 9:31

2 Answers 2

4

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)

Sign up to request clarification or add additional context in comments.

3 Comments

Ok that explains a lot, is there a way to log the current state of an Array?
JSON.stringify() or clone it (a.slice(0))
...or console.log(a + ''); console.log(a.join(','));
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.