Matt Mazur
Matt Mazur

Reputation: 998

Unexpected behavior with Javascript object literal notation

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.

Upvotes: -1

Views: 214

Answers (1)

user1106925
user1106925

Reputation:

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('---');

Upvotes: 3

Related Questions