-1

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.

2
  • 2
    stackoverflow.com/a/8249333/798880 Commented Apr 9, 2012 at 1: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. Commented Apr 9, 2012 at 1:55

1 Answer 1

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('---');
Sign up to request clarification or add additional context in comments.

1 Comment

@bfavaretto: I think you're right about that. Definitely in Chrome. I'll update.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.