Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy doesn't console.log() take a snapshot of the passed variables?
    primarykey
    data
    text
    <p>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:</p> <pre><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); </code></pre> <p><a href="http://jsfiddle.net/UNWEp/" rel="noreferrer">The code at jsFiddle</a></p> <p>The output of this is something like (depending on the browser):</p> <pre><code>&gt; Object 50 </code></pre> <p>If you expand the "Object" (in Chrome, Safari or Firefox (Firebug) what you get is:</p> <pre><code>&gt; Object left: 0 top: -50 </code></pre> <p>Whereas I would expect:</p> <pre><code>&gt; Object left: 50 top: -50 </code></pre> <p>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.</p> <p>Or is there something else going on?</p> <p><strong>Edit:</strong> 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).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload