What reasoning causes the .sort method to impact multiple variables instead of just the one it's used on?

The complexity of the following scenario has left me utterly perplexed:

x = 5
y = x
z = x
z = z + 1

results in

x = 5
y = 5
z = 6

However, when dealing with arrays, as seen below:

x = ["z", "x", "y"]
y = x
z = x
z = z.sort()

results in

x = ["x", "y", "z"]
y = ["x", "y", "z"]
z = ["x", "y", "z"]

It seems that changing a value in a variable only affects that specific variable - which makes sense. But when using methods like .sort(), it appears to impact other variables in a surprising way due to some sort of intricate reassignment logic. Can someone shed light on this for me? I feel completely disoriented and find it rather counterintuitive.

Answer №1

In JavaScript, arrays are considered objects. The values of objects in JavaScript are actually references. When you assign an object to multiple variables, those variables point to the same object. So, after this:

x = ["b", "a", "c"]
y = x
z = x

there is only one array involved.

If you want to create a copy of an array, you can do it like this:

z = x.slice(0);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Submitting form data using AJAX POST method and serializing it

I attempted to submit form data using an onclick event within an ajax function, but unfortunately the data is not being posted on the next page. I utilized the serialize method for form data submission but encountered issues with its functionality. Interes ...

Arranging elements within an outer array by the contents of their inner arrays

I need help organizing an array based on the alphabetical order of a specific value within the inner arrays. For example: I want to sort this array by the prefix "old," so old A, old B, etc. const array = [ { personName: "Vans", personTags: ["young", " ...

The alert box is not displaying, only the text within the tags is visible

Trying to implement an alert message for logged-in users. A successful login will trigger a success message, while incorrect username or password will display an error. function showMessage(response) { if (response.statusLogged == "Success login") { ...

When the div alters the content

Is it possible to hide a div after another div changes its content with a button click? For example, when I click on the submit button, the <div id="dynamic">1</div> changes to <div id="dynamic">2</div>. Once it ...

Issue connecting to servers within the designated MongoDB Atlas Cluster has caused a mongoDB error

const mongoose = require('mongoose'); mongoose.connect('mongodb://DATABASE_LOGIN1:[MyPass]@mee6copycluster-shard-00-00.r86qy.mongodb.net:27017/djsdashboard/?authSource=admin', { useNewUrlParser: true, useUnifiedTopology: true, }); ...

Schema Connections in Kendo Diagram

I am currently experimenting with the Telerik Kendo diagram in an attempt to create a visual representation. Due to the fact that I am retrieving all shapes and their connections from my database, I encountered an issue where the attributes of my data sour ...

The feature to "Highlight text on the page" in React-pdf is currently malfunctioning

I am currently working on incorporating the pdf highlighting feature from React-pdf: import React, { useMemo, useState } from 'react'; // import { Document, Page } from 'react-pdf'; import { Document, Page } from 'react-pdf/dist ...

Sending base64 URLs from Android WebView to Javascript can be tricky due to the limitation on the URL length, which may result in a refusal

Trying to send a base64 image to JavaScript is proving challenging as I keep encountering an error in Android Studio: W/chromium: [WARNING:navigator_impl.cc(280)] Refusing to load URL as it exceeds 2097152 characters. Despite attempting to use loadDataWi ...

The dialog box is refusing to appear as a modal popup - shadcn

I recently integrated the Dialog component from shadcn into my next.js project. However, I am encountering issues as it is not behaving like a typical modal or popup. Here is a screenshot for reference: https://i.sstatic.net/fVkQz86t.png return ( < ...

What could be causing my variables to not update in Node.js?

I recently developed a web application using node.js that is designed to receive messages from an SNS topic through a POST request. The messages are then logged to the console and displayed on the webpage. However, I noticed that when I publish a message t ...

Real-time collaborative Whiteboard using WebSocket technology (socket.io)

I am currently working on developing a collaborative online whiteboard application using HTML5 canvas, Node.js, and Websockets (Socket.io). While my progress is going well, I am facing some challenges when it comes to drawing circles. I have been successfu ...

Is it possible to make the entire div clickable for WordPress posts, instead of just the title?

I am currently facing an issue where only the h1 element is linked to the post, but I want the entire post-info div to be clickable. Despite my efforts, I haven't been able to make the whole div clickable, only the h1 element remains so. Below is the ...

Update a Div, Table, or TR element without the need for a page reload or Ajax usage

How can I refresh a div, table or <tr>? The data displayed is not coming from a database, it's just a simple error block and the value comes from Java-script. The issue arises when a user inputs a value in a textbox, the value gets stored in th ...

Encountering the value of 'undefined' when using jQuery

I need help with displaying values in my asp.net application using ajax. Here is the C# code snippet: [WebMethod] public static string fillvazh(int id) { List<object> Users = new List<object>(); DataTable dt = new DataTable(); ...

Adding routes and components dynamically with Mithril is a dynamic and versatile feature to enhance your

The official website of Mithril mentions that only one m.route call is allowed per application. Despite this limitation, I was able to find a workaround using code splitting. However, my application is designed to recognize only the first-level compone ...

Error loading Azure Active Directory web form: Server returned a 401 status code for the requested resource

I recently made changes to my web site (incorporating a web form and entity framework) to use AAD connection, following the guidance in this insightful blog post. However, I am encountering an issue where scripts and css files are not loading properly. Th ...

Populating a dropdown with a list by utilizing the append grid library

Hey there! I'm currently using the jquery appendGrid plugin to display a drop-down menu in one of the columns. In the code snippet below, the column labeled "Origin" has a drop-down option that is working as expected. $(function () { // Initializ ...

Adjusting element position while scrolling

Objective The goal is to have the page navigation display lower on the page by default. This will provide a cleaner layout as shown in the image below. Context An interactive element for navigation was implemented utilizing Headroom.js. This library d ...

Any suggestions on how to incorporate the variable into the inline JavaScript [[]] API path?

I have a query regarding creating a URL in JavaScript, but I'm unsure how to include variables within th:inline="javascript". Below is my code snippet: <script th:inline="javascript"> $(function() { $('#querySubmit').click(queryS ...

Dimming the background of my page as the Loader makes its grand entrance

Currently, I am in the process of developing a filtering system for my content. The setup involves displaying a loader in the center of the screen whenever a filter option is clicked, followed by sorting and displaying the results using JQuery. I have a v ...