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
Release: 2024-12-13 01:15:10
Original
396 people have browsed it

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]
Copy after login

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)));
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template