search

Home  >  Q&A  >  body text

console.log() displays the changed value before the variable value actually changes

<p>I understand this code. We copy A and call it C. When A changes, C remains unchanged</p> <pre class="brush:php;toolbar:false;">var A = 1; var C = A; console.log(C); // 1 A; console.log(C); // 1</pre> <p>But when A is an array, the situation is different. Not only does C change, but it changes before we touch A</p> <pre class="brush:php;toolbar:false;">var A = [2, 1]; var C = A; console.log(C); // [1, 2] A.sort(); console.log(C); // [1, 2]</pre> <p>Can someone explain what is happening in the second example? </p>
P粉427877676P粉427877676498 days ago562

reply all(2)I'll reply

  • P粉023326773

    P粉0233267732023-08-28 15:10:01

    console.log() will pass a reference to the object, so the value in the console will change as the object changes. To avoid this you can:

    console.log(JSON.parse(JSON.stringify(c)))

    MDN WARNING:

    reply
    0
  • P粉795311321

    P粉7953113212023-08-28 12:26:58

    Pointy's answer provides good information, but it is not the correct answer to this question.

    The behavior described by the OP was part of a bug first reported in March 2010 and patched for Webkit in August 2012, but has not yet been integrated into Google Chrome as of this writing. Behavior depends on whether the console debug window is open or closed when passing an object literal to console.log() .

    Excerpt from the original bug report (https://bugs.webkit.org/show_bug .cgi?id=35801):

    Chromium Developer Response:

    A lot of complaints ensued, which eventually led to a bug fix.

    Changelog description for patch implemented in August 2012 (http://trac.webkit.org/changeset/ 125174):

    reply
    0
  • Cancelreply