bbrame
bbrame

Reputation: 18554

Javascript unexpected console output with array assignment;

I am getting unexpected console output after array assignment in webkit browsers (Chrome 16.0.912.77 and Safari 5.1.2 - 7534.52.7).

Here is my function that demonstrates the error:

function test() {
    var myArray = [];
    console.log(myArray); // Should be [], but is [0]
    myArray.push(0);
}

I receive the expected output of [] in Firefox 7.0.1.

[EDIT]

When I insert a long synchronous sleep, the problem doesn't go away. This makes me think that (1) even though the console.log statement is asynchronous, it is running in the same thread and (2) it is waiting until the event queue is empty before it runs and (3) the reference passed to console.log is being turned into a string when console.log is finally executed - not when it is called.

function sleep(millis){
  var date = new Date();
  var curDate = null;
  do { curDate = new Date(); }
  while(curDate-date < millis);
}

function test() {
    var myArray = [];
    console.log(myArray); // Should be [], but is [0]
    sleep(2000);    
    myArray.push(0);
}

This doesn't seem like desired behavior.

Upvotes: 3

Views: 874

Answers (1)

Ry-
Ry-

Reputation: 225164

This is because console.log is by reference and asynchronous, and your push() ends up executing before the result is displayed.

You could do a quick:

console.log(myArray.slice());

Instead, for debugging purposes.


To test this more obviously:

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

will give [1, 2, 3, 4, 5].

var a = []; console.log(a); setTimeout(function() {a.push(1, 2, 3, 4, 5);}, t);

gives the wrong result for me with t = 5 and the right result for t = 100.

Upvotes: 6

Related Questions