0

not a js expert so this might be a stupid question but...

Why does the log show that the array has changed? I was expecting the array still to be a [0,0] since the method is invoked after the console.log. Also, if I try to replace the whole array like this:

this.my_array = [1,0];

the log will still show [0,0], which is something that makes more sense to me. What's going on?

function Y() {        
  this.my_array = [0,0];            
  this.changeIt = function() {
    this.my_array[0] = 1;
  };
}

var z = new Y;
console.log(z.my_array);
z.changeIt();

3
  • 1
    Please don't ask two separate questions intermingled, it makes it very hard to understand, and it makes it hard for answers to be clear. Commented Nov 5, 2012 at 12:18
  • 1
    What's interesting is that stepping through the code in Chrome outputs [0,0], but executing it outright outputs [1,0]. Commented Nov 5, 2012 at 12:18
  • I'm actually getting [0,0] when I run this in the commandline (Firebug). Commented Nov 5, 2012 at 12:18

2 Answers 2

7

In some browsers (Chrome, for instance) console.log displays a live, interactive display of your array, not a point-in-time snapshot. So if you're looking at the console after this runs, it's been updated because of the change. Chrome also does slightly different things when you use console.log interactively in the console panel than when you use it from within a script.

You'll see what you're expecting if you display a string instead:

var z = new Y;
console.log(z.my_array.join(", "));
z.changeIt();

That shows the point-in-time snapshot you're expecting.

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

3 Comments

But then why isn't the console.log display updated in its place if run z.myarray[0]=2 in the Chrome console?
nice catch and nice answer, however... +1 now :)
@chumkiu: Thanks. This is actually something I learned here at SO, but I can't find that question now to link to it...
0

It works for me: http://jsfiddle.net/LyhgW/

Edit: The fact that i'm using alert makes this code work. This works around Chrome's live-feature in the console and displays a snapshot instead.

2 Comments

alert and console.log are very different things.
@ Lukas: It does on Chrome. Using an updated version of your fiddle, I see [1, 0] twice in the console. As chumkiu points out, Firefox doesn't do the "live" thing either, but Chrome does.

Your Answer

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