What causes JS-Objects to exhibit such behavior?

let firstObject = { x: 0, y: 0 };
let secondObject = firstObject;
secondObject.y = 1;

After this operation, firstObject.y equals to 1.

What is the reason behind this behavior and how can I prevent firstObject.y from changing?

Answer №1

Alpha and beta both point to the same memory location in the allocated heap, so any changes made to one object will be immediately reflected in the other since they essentially refer to the same object.

To avoid this issue, it is recommended to copy all properties from alpha to beta by iterating through each property and assigning its value to the corresponding property in beta.

var alpha = { a: 0, b: 0 },
beta = { };

for(var prop in alpha){
     if(alpha.hasOwnProperty(prop)){
        beta[prop] = alpha[prop];   
     }
}

In more complex scenarios where you have nested objects like:

var alpha = {
    propA: {},
    propB: {}
}

Deep cloning is required to recursively clone these complex properties to avoid reference issues.

If using jQuery, you can utilize the extend method for deep copying:

 $.extend(true, beta, alpha)

Answer №2

alpha and beta refer to the same object.

To create a copy of the alpha object, you need to clone it. There are various implementations available if you search for them.

Since your question includes the JSON tag, here is a simple implementation (not suitable for cyclic objects):

var beta = JSON.parse(JSON.stringify(alpha));

Answer №3

When a JavaScript variable holds a reference to an object, it's important to clone the object in order to sever the connection to alpha.b.

To learn more about efficient ways to deep clone an object in JavaScript, check out: What is the most efficient way to deep clone an object in JavaScript?

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

Implementing JavaScript in a VB.NET Application

My current project at the office involves developing a VB.NET application to streamline and partially automate our work processes. One task within this project requires downloading a .pdf file from our intranet. To achieve this, we utilize IE through a sc ...

Put emphasis on the input field - React component

My React component features an input field with a disabled attribute. When the component is clicked, the input becomes enabled for the user to type in. I have successfully implemented this functionality so far, but now I need to focus on the input field on ...

Proceed to the following JSON entry once ijson.common.IncompleteJSONError is encountered

I am facing a challenge with parsing a large JSON file containing approximately 11,600 records using ijson in Python. The issue arises when the for loop encounters one corrupt JSON record, causing the iteration to break. Is there a method to skip this prob ...

Having trouble sending HTTP requests in Angular 6

I am currently facing an issue in my Angular application while trying to send an HTTP POST request to a Spring RESTful API. Despite my attempts, I have not been able to succeed and I do not see any error response in the browser console. Below is a snippet ...

The HTML5/JQuery/JSON webpage is currently experiencing difficulties retrieving data

I'm having trouble with the code below. It's not displaying anything. Can anyone help me fix it? <!DOCTYPE html> <html> <head> <title>Flight Data</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/ ...

The step-by-step guide to incorporating a new key-value pair into a JavaScript object

I have a group of objects that look like this [ { name: "ABC", grade: 2 }, { name: "DEF", grade: 3 }, ..... ] My goal is to add an additional key-value pair to each object in the array, resulting in the follow ...

Unresponsive IE browser: Issues with jQuery event changes and click functionalities

Here is the HTML code: <div class="sss"> <label class="label_radio" for="radio-01"> <input name="vtip" id="radio-01" value="50" type="radio" /> <img src="http://www.tui-travelcenter.ro/layouts/innobyte/images/radio ...

Ways to extract data from MySQL and convert it into JSON format

When working with arrays, everything goes smoothly. However, when dealing with single line information, I seem to hit a roadblock. In my JSON output: $sql3 = mysql_query("SELECT description_fr FROM aboutUni where id = 1" ); $query = mysql_query("SELECT ...

Is it appropriate to include a function within a loop?

I'm curious to know if it's considered good practice to call a function inside a loop. Both of the following code snippets produce the same result, but I want to add clarity by using a function. Is this considered good practice? Thank you. Code ...

Developing a user-friendly widget for a website that is not optimized for mobile devices

Here's the backstory: I'm currently in the process of creating a mobile-friendly widget for my clients. Unfortunately, they have web pages that are not optimized for mobile devices, and it doesn't seem like that will change anytime soon. Th ...

Formatting dates in the Bootstrap Date Picker within Angular 6

When using Angular 6, I incorporate a date picker by adding the bsDaterangepicker class for selecting a date range. <input type="text" (ngModelChange)="dateFilterChanged($event)" [(ngModel)]="myDateField" value="{{ myDateField | date:'yyyy-MM-dd&a ...

Click on the link to see the jQuery effect in action

I'm trying to achieve a fade-out effect on the current page followed by fading in a new one. The fade-in effect is working fine, but when I click on the link, the new page loads without first fading out the existing content. The div that I want to app ...

Tips for minimizing the frequency of useEffect triggering?

After receiving a disappointing performance score from Google's lighthouse tool for my app, I decided to investigate further. One component in particular caught my attention - Home. Within the Home component, there is a useEffect hook that looks like ...

Attempting to create a pathway for removing a profile and user from mongoDB

Hello, StackOverflow community! This is my initial post here and I'm excited to seek guidance. I recently created a delete route in Express to delete both a user and their profile: // @route DELETE api/profile/ // @desc Delete user and profile / ...

TypeScript Error: The Object prototype must be an Object or null, it cannot be undefined

Just recently, I delved into TypeScript and attempted to convert a JavaScript code to TypeScript while incorporating more object-oriented features. However, I encountered an issue when trying to execute it with cmd using the ns-node command. private usern ...

Can AdonisJS 4.1.0 support conditional queries?

I am exploring the capabilities of AdonisJs query builder by referring to their documentation at Currently, I am attempting to replicate a scenario similar to the one demonstrated under the 'Conditional Queries' section: const query = Database. ...

The custom filter in AngularJS fails to activate

Currently, I have a filter function that looks like this: 'use strict'; angular.module('app') .filter('fromNow', function() { return function(date) { return moment(date).fromNow(); } }); ...

Retrieving JSON data without keys using jansson

I need to extract values from a JSON file that lacks the key descriptor preceding the values, with the values being separated by a colon instead. Below is an example of the input format I am working with: {"out":[[0.2,15],[0.5,3.3],[0.1,46.8]],"in":[[0.6 ...

What is a more sophisticated approach to adding css to "every element except this one"?

I am currently using html/jQuery to create tabbed navigation on my website. I have managed to make the selected tab appear active by adding a CSS class "active" and changing the previous tabs to have an "inactive" class. In order to achieve this, I have in ...

Despite containing data, the JSON object continues to display as undefined

I'm encountering an issue with my json data. I'm able to access all the key's values such as ._id and price, but I'm struggling to access retailer and retailer_slug. Despite numerous attempts, I can't seem to figure out what I&apos ...