There are two references to an object, but even if one of them is modified, the second reference continues to show the

During my attempts to troubleshoot an issue in a JS plugin, I noticed that one variable was sometimes affecting another and sometimes not. In order to investigate further, I added the following code:

var a = $('#w3').data('fileinput').initialPreviewConfig[index];
var b = previewCache.data[id].config[index];
if (a === Object(a) && b === Object(b)) { //check a and b are objects
   if(a == b && a === b) { //check they reference same object
      a = null; //set a to null, so b should be null as well
      if(a === null && b !== null) {
         console.log("This should not be printed!"); //but it is not!
      }
   }
}

The output displays This should not be printed.

I'm puzzled by why modifying one variable does not affect the other when both are pointing to the same object. Could this be due to an event or perhaps an overridden operator?

Edit: In an attempt to simplify the code, removing variables 'a' and 'b' results in sometimes showing This should not be printed, sometimes not.

if ($('#w3').data('fileinput').initialPreviewConfig[index] === Object($('#w3').data('fileinput').initialPreviewConfig[index]) && previewCache.data[id].config[index] === Object(previewCache.data[id].config[index])) {
   if($('#w3').data('fileinput').initialPreviewConfig[index] == previewCache.data[id].config[index] && $('#w3').data('fileinput').initialPreviewConfig[index] === previewCache.data[id].config[index]) {
      $('#w3').data('fileinput').initialPreviewConfig[index] = null;
      if($('#w3').data('fileinput').initialPreviewConfig[index] === null && previewCache.data[id].config[index] !== null) {
            console.log("This should not be printed!");
      }
   }
}

Answer №1

Implementing this process

x = undefined

Only affects the value of null on variable x.

The state of variable y remains unchanged.

In JavaScript, variables can be viewed as named references to data stored in memory locations.

For instance, consider the code snippet below:

var obj = { animal: 'bear' };
var x = obj;
var y = obj;

This results in two variables, x and y, both pointing to the same object (obj) in memory.

When you execute

x = null

You are only redirecting x to point at null, while y continues pointing to obj.

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

Tap on the HTML5 video to exit the fullscreen mode

Objective I have successfully implemented a fullscreen video setup that triggers when a link is tapped on a mobile device. To maintain a clean aesthetic, I have hidden the HTML5 video controls using CSS. The desired functionality includes closing the full ...

Postman post request failing to insert Mongoose model keys

Recently, I've been experimenting with the post method below to generate new documents. However, when I submit a post request in Postman (for example http://localhost:3000/api/posts?title=HeaderThree), a new document is indeed created, but unfortunate ...

Unable to invoke a custom hook within another custom hook in a React application

I've developed a React application using create-react-app. Currently, I'm working on creating a custom hook that integrates with the Microsoft Authentication Library (MSAL). MSAL provides a custom React hook that I want to utilize within my own ...

The Angular TypeScript service encounters an undefined issue

Here is an example of my Angular TypeScript Interceptor: export module httpMock_interceptor { export class Interceptor { static $inject: string[] = ['$q']; constructor(public $q: ng.IQService) {} public request(config: any) ...

What sets apart toBeInTheDocument from getBy* in @testing-library/react?

Can you distinguish between these two methods in react-testing-library? expect(screen.queryByText('<something>')).toBeInTheDocument(); And screen.getByText('<something>'); (The specific getBy* and queryBy* operation are no ...

Using Vue.js to toggle rendering based on checkbox selection

Struggling to conditionally render form elements in Vue based on user input. I can do this with VanillaJS or jQuery, but struggling to implement it with Vue's built-in conditional directives. Using single-file components with the webpack template from ...

"Troubleshooting the issue of Angular UI-Select failing to display a large

Check out my comprehensive json file containing cities from around the world: download here. Furthermore, take a look at the snippet of html code below: <div class="form-group"> <label class="control-label"> CITY </label> ...

Include a description in the cell of the table

I am struggling with adding a small description below one of the columns in my three-column table. I have tried using Grid, but so far, nothing has worked for me. Can anyone provide assistance? To give you a better idea, I have highlighted the desired res ...

I would appreciate your assistance with the hide button

Is there a way to hide a button after clicking on it? I would greatly appreciate your help! ...

We could not locate the requested resource with a DELETE request using the fetch JSON method

Currently, I am in the process of developing a webpage that utilizes JSON API REST alongside XAMPP with an Apache server. Up until now, everything has been working smoothly as I have been utilizing the DELETE method successfully. However, I seem to have hi ...

Updating a $scope variable within a loop in AngularJS

Attempting to modify a $scope variable: Example: $scope.variable_1 $scope.variable_2 ... Desired way of updating it: for (i=0; i<2; i++) { $scope.variable_$i = 1; } Wanting to access "$scope.variable_1" using the "i" index in each loop. Any ...

Is async/await necessary even if the outcome is not important to me?

Imagine I have an API call that performs X and I convert it into asynchronous code using async/await: export default async (req: NextApiRequest, res: NextApiResponse) => { let success = await sendEmail({ //... }); return res.status(200) ...

Guide on submitting a form through the Angular 2 HTTP post method with JavaScript

Currently working on grasping the concepts of Angular2, but facing challenges when attempting to utilize http.post() for submitting a form to my Web API. ...

Shift div position when clicked and employ jQuery animations

I have been attempting to add animation to a DIV element by using jQuery. The goal is to move the DIV from the center to the left when it is clicked, but I am encountering some issues. The parent div has a position of "relative", and my initial idea was to ...

JS: delay onClick function execution until a page refresh occurs

Currently, I am working on a WordPress site that involves a form submission process. Upon successful submission, a new post is created. After the user submits the form, I have implemented JavaScript to prompt them to share a tweet with dynamically prepopu ...

Obscure Promise Structure - Accomplish, Flop, Achieved

I came across the following code block and I'm struggling to understand it. While I have a good grasp on promises in the context of: deferred.then(successCb, errorCb); This code snippet appears to have three callbacks (complete, fail, done>) whic ...

Learn how to establish a state using an array and effectively utilize the setState() method in React

For my latest project, which is API based, I am working with arrays that contain sub-arrays. How can I define a state with an array and utilize the setState() method to work with the entire array? ...

Transfer the values selected from checkboxes into an HTML input field

I am attempting to capture the values of checkboxes and then insert them into an input field once they have been checked. Using JavaScript, I have managed to show these values in a <span> tag successfully. However, when trying to do the same within a ...

Unable to load the first tab in Material-ui V3 after fetching data or when the page loads

After using Material UI version 3 scrollable-tab and fetching data to load tabs and tab container, I encountered an issue where the first tab does not automatically load on page load. It requires a click in order to see the information. I have searched on ...

The Google Maps directions stay visible even when new routes are generated

Utilizing the Google Maps Javascript API V3 in my Android WebView has presented a new issue. When I request directions from point A to B, it displays correctly. However, when I switch the endpoints to go from A to C, the route from A to B does not disappea ...