0

I've been experimenting with using Javascript object literal notation vs functions with prototypes and have run into a bug I can't figure out.

Here's the relevant code:

var MyTestObj = {

  myTestFunction: function() {
    var myArray = []

    console.log('Before:');
    console.log(myArray);
    console.log(myArray.length);
    console.log('---');

    for (var mi = 0; mi < 5; mi++) {
      myArray.push(1);
    }

    return myArray;
  }
}

When I call console.log(myArray) I expected it to output [], but instead I get this:

> MyTestObj.myTestFunction()
  Before:
  [1, 1, 1, 1, 1]
  0
  ---
  [1, 1, 1, 1, 1]

Can someone explain why myArray already has a value when I output it prior to the loop? And why does it output the correct length (0) immediately afterwards?

Appreciate the help.

Matt Mazur
  • 980
  • 1
  • 10
  • 22
  • 2
    http://stackoverflow.com/a/8249333/798880 – Saxoier Apr 09 '12 at 01:55
  • Logging to the console is a weirdly slow operation, I think it's just a performance issue there... By the time it gets around to actually writing it, it's been populated. Happens to me occasionally where I'll log an object that gets destroyed/cleared out, and I can't access any of its properties. – JKing Apr 09 '12 at 01:55

1 Answers1

3

It's a quirk of Chrome and Safari's console. It doesn't evaluate the Array immediately for display.

If you .slice() it, it'll show up properly since the Array has only primitives.

console.log('Before:');
console.log(myArray.slice()); // <-- copy the Array
console.log(myArray.length);
console.log('---');
  • @bfavaretto: I think you're right about that. Definitely in Chrome. I'll update. –  Apr 09 '12 at 01:56