Home >Web Front-end >JS Tutorial >Why Does `console.log()` Show Immediate Array Changes in JavaScript?
console.log() Echoes Changes in Array References Instantly
In JavaScript, variables holding primitive values like numbers and strings are passed by value, while those containing objects are passed by reference. This distinction becomes apparent when manipulating arrays.
Consider the following code:
var A = [2, 1]; var C = A; console.log(C); // [1, 2] A.sort(); console.log(C); // [1, 2]
In this example, C is assigned a reference to the array A. When A is sorted, the changes are immediately reflected in C, even before A is accessed again.
Why does this occur? Unlike primitive values, objects are heap allocated, meaning they reside in the computer's memory and are accessed through a reference. When we log C, console.log() prints the reference to the array and not a copy of its contents. Thus, any subsequent modifications to the referenced object (in this case, sorting the array) will also be seen in the console before A is used again.
To avoid this behavior and log a snapshot of the object at the instant console.log() is called, you can use the following trick:
console.log(JSON.parse(JSON.stringify(C)));
This technique creates a deep copy of the object using JSON serialization and deserialization.
The above is the detailed content of Why Does `console.log()` Show Immediate Array Changes in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!