Home >Web Front-end >JS Tutorial >Why Does `console.log()` Show Immediate Array Changes in JavaScript?

Why Does `console.log()` Show Immediate Array Changes in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-13 01:15:10397browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn