0

Possible Duplicate:
console.log object at current state

I understand basic synchronous and asynchronous behavior:

// this block gets executed all at once the next time the js engine can run it
setTimeout(function() { 
    var snacks = "cookies";
    snacks += "and popcorn";
    console.log("goodbye world"); 
}, 0);

console.log("hello world"); // this block runs before the block above

What I don't understand why the first console here reports[]:

var x = [];
x.push({ a: "c" });
console.log(x); // says []
x.splice(0, 1);
console.log(x); // says []
Community
  • 1
  • 1
user1757120
  • 323
  • 2
  • 13
  • 3
    It's buffering issues probably. Works ok ([Object:...]) in first case for me, btw. – raina77ow Oct 23 '12 at 16:34
  • Consider changing the question. And what has the 1st code block got anything to do with second block? Just fire up chrome console and type in the commands there and see how it goes. – specialscope Oct 23 '12 at 16:40
  • @specialscope The question is clear and it states how the code goes, whats asked is why it happens :) – Alok Swain Oct 23 '12 at 16:44
  • Please enlighten me with the meaning of "execution block" in javascript. – specialscope Oct 23 '12 at 16:47
  • That ("execution block") is just a phrase I made up. I don't know what it's actually called. – user1757120 Oct 23 '12 at 16:54
  • You should definitely change that :) – Alok Swain Oct 23 '12 at 16:55
  • If you execute the second code sample from the question in Firefox, you would see that the logs are correct. It logs the runtime values of the Array at that point, Chrome seems to take time to log the value, pretty sure it must have been posted somewhere in v8 issues or something.. there have been some such differences between Gecko(FFx JS engine) and v8(Chrome JS engine) engine where the results differ, apparently V8 does some of the these things to achieve its performance – Alok Swain Oct 23 '12 at 17:00
  • 1
    duplicate of [console.log object at current state](http://stackoverflow.com/questions/7389069/console-log-object-at-current-state), [Wrong value in console.log](http://stackoverflow.com/q/11214430/1048572) and [Is JavaScript console lazy about evaluating arrays?](http://stackoverflow.com/questions/4057440/) – Bergi Oct 23 '12 at 17:23

1 Answers1

0

It's an issue of the console itself—it shows you the current value. The actual value is what you would expect. This behavior does not affect primitive values (strings, numbers, booleans, null, undefined) you log.

Try logging the array serialized.

var x = [];
x.push({ a: "c" });
console.log(JSON.stringify(x)); // says '[{"a":"c"}]'
x.splice(0, 1);
console.log(JSON.strinfigy(x)); // says '[]'

And just a note about the first code example: It is not completely correct that the first block gets executed second. The setTimeout call is made before the console.log call at the end—it's only the callback function passed to setTimeout that gets executed later.

J. K.
  • 8,268
  • 1
  • 36
  • 35