11

I have the following code:

console.log("start");
for(var i = 0; i < array.length; i++){
    console.log(i + " = " + array[i]);
}
console.log(array);
console.log("end");

This gives me the following output:

[16:34:41.171] start
[16:34:41.171] 0 = 0
[16:34:41.172] 1 = 168
[16:34:41.172] 2 = 171
[16:34:41.172] [0, 168, 171, 139]
[16:34:41.172] end

That is, it doesn't show the 139 element when iterating the array, but console.log does print it when outputting the whole array. WHY? (<-- the question)

I do modify the array later on, is the console.log somehow delayed until after I changed the array? Note tho that change the order of the statements, and putting consoel.log(array) directly at the start does not change the outcome (still different outputs).

I am using firefox 20.0

user1302914
  • 191
  • 1
  • 2
  • 8
  • 2
    How/where is your array defined? I'm not seeing what you are: http://jsfiddle.net/j08691/vJd6x/ – j08691 May 10 '13 at 14:43
  • 1
    possible duplicate of [JavaScript: console.log() gives different results than alert()](http://stackoverflow.com/questions/15528322/javascript-console-log-gives-different-results-than-alert) – Rob W May 10 '13 at 14:46
  • Is the array an object property? http://stackoverflow.com/questions/8249136/why-does-javascript-object-show-different-values-in-console-in-chrome-firefox/8249333#8249333 – Alex K. May 10 '13 at 14:47
  • Rob W: that answered my question thanks. I had assumed that console.log was instant and blocking, turns out it isn't :) – user1302914 May 10 '13 at 15:29
  • It seems I cannot accept the duplicate as a correct answer (which was first). So I have accepted Daniel's answer. Thanks all – user1302914 May 10 '13 at 22:16

1 Answers1

16

Update: If you want to see this behavior, copy and paste the code in the console and execute. Then close developer tools and open again, apparently the pointer thing only happens when the code is executed in the background(which happens when you reopen the console).

Console.log output of objects, is a pointer, no a real value. This means that if the object changes later, console.log object will be updated. Try:

console.log("start");
var array = [1];
for(var i = 0; i < array.length; i++){
    console.log(i + " = " + array[i]);
}
console.log(array);
console.log("end");
array.push(9999);// you will see the 9999 in the console no matter it was added after the output.

To prevent pointer issues try this: console.log(array.join()); because later in some point of your application you are adding the 139 value.

Daniel Aranda
  • 6,426
  • 2
  • 21
  • 28