This bit of code I understand. We make a copy of A and call it C. When A is changed C stays the same
var A = 1;
var C = A;
console.log(C); // 1
A++;
console.log(C); // 1
But when A is an array we have a different sitiuation. Not only will C change, but it changes before we even touch A
var A = [2, 1];
var C = A;
console.log(C); // [1, 2]
A.sort();
console.log(C); // [1, 2]
Can someone explain what happened in the second example?
Though it's not going to work in every situation, I ended up using a "break point" to solve this problem:
Arrays are objects. Variables refer to objects. Thus an assignment in the second case copied the reference to the array from "A" into "C". After that, both variables refer to the same single object (the array).
Primitive values like numbers are completely copied from one variable to another in simple assignments like yours. The
A++;
statement assigns a new value to "A".To say it another way: the value of a variable may be either a primitive value (a number, a boolean,
null
, or a string), or it may be a reference to an object. The case of string primitives is a little weird, because they're more like objects than primitive (scalar) values, but they're immutable so it's OK to pretend they're just like numbers.EDIT: Keeping this answer just to preserve useful comments below.
@Esailija is actually right -
console.log()
will not necessarily log the value the variable had at the time you tried to log it. In your case, both calls toconsole.log()
will log the value ofC
after sorting.If you try and execute the code in question as 5 separate statements in the console, you will see the result you expected (first,
[2, 1]
, then[1, 2]
).Pointy's answer has good information, but it's not the correct answer for this question.
The behavior described by the OP is part of a bug that was first reported in March 2010, patched for Webkit in August 2012, but as of this writing is not yet integrated into Google Chrome. The behavior hinges upon whether or not the console debug window is open or closed at the time the object literal is passed to
console.log()
.Excerpts from the original bug report (https://bugs.webkit.org/show_bug.cgi?id=35801):
Response from a Chromium developer:
Much complaining ensued and eventually it led to a bug fix.
Changelog notes from the patch implemented in August 2012 (http://trac.webkit.org/changeset/125174):
Console.log() will log the object hence the value will change in the print. To avoid this do the following:
For more information https://developer.mozilla.org/en-US/docs/Web/API/Console/log