Alex Rivera | Logout

Why doesn't console.log() take a snapshot of the passed variables?

Asked 2011-03-07T18:20:25.273
19

I've ran into some really weird behavior with javascript today. I think I got it somehow figured out now, but I'd like to know if what I think is going on is really happening or if there is some other magic involved. So this is my code:

    var SomeObject = {};

    SomeObject.foo = function(a, b) {
       var baz = this.bar(a, b);
       console.log(baz);
       console.log(baz.left);
       SomeObject.magicalStuff(baz);
    };

    SomeObject.bar = function(a, b) {
        return {left: a-b, top: b-a};
    };

    SomeObject.magicalStuff = function(position) {
        position.left = 0;
    };

    SomeObject.foo(100, 50);

The code at jsFiddle

The output of this is something like (depending on the browser):

> Object
50

If you expand the "Object" (in Chrome, Safari or Firefox (Firebug) what you get is:

> Object
    left: 0
    top: -50

Whereas I would expect:

> Object
    left: 50
    top: -50

What I think is going on is that console.log() really just "posts" a reference to the console, which gets read once you click on the "expand" symbol. But doesn't that kind of defeat the purpose of console.log() as a debugging instrument? I always expected console.log() to "snapshot" the stuff I pass to it. It is really surprising to see a statement which comes after the actual console.log() change the output of that very console.log() call.

Or is there something else going on?

Edit: I'm also wondering if there is a sound reason for browser developers to implement console.log like this (I guess there is one, otherwise it wouldn't be consistent across major browsers).

Edit
Report

1 Answer

6

I've also seen this behavior and it sure looks like a reference is posted. To get around this I used the clone() method in jQuery on the things I wanted to log.

answered 2011-03-07T18:25:24.307

Your Answer