Javascript Console Log reporting object properties incorrectly

The browser doesn’t save the whole object when you call console.log(), just a reference to it. When you inspect it later, the browser will get the current version of the object.

You can test this quite simple by appending a new element to the object.

Call this at the end:

var newAppData = {
    "2": {
        name: "a",
        age: 443
    }
}

In the console it’ll show up as

Object {0: Foo, 1: Foo}
Object {0: Foo, 1: Foo, 2: Foo}

but when you open the first log entry, you will see all three elements, so the browser inspects the current version.

Demo: https://jsfiddle.net/n302nsbh/22/

Solution 1

To see the current version of an element of the object, directly refer to it with console.log(fooManager.objects[0]); This will output for your script:

Foo {name: "a", age: 2}
Foo {name: "a", age: 443}

Demo: https://jsfiddle.net/n302nsbh/23/

Solution 2

Just found another nice solution at https://stackoverflow.com/a/7389177/1682509

Use console.log(JSON.parse(JSON.stringify(fooManager.objects))); to get a browsable snapshot.

Demo: https://jsfiddle.net/n302nsbh/24/

Leave a Comment