andrzej1_1
andrzej1_1

Reputation: 1193

Two references to object, but when modify it by one, second still show unchanged object

I am trying to fix an issue in a JS plugin and after debugging I discovered that sometimes one variable is changing another, sometimes not. So I placed this 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!
      }
   }
}

and the output is This should not be printed.

If both variables are pointing to same object why modifing by one does not change another? What can cause this, event or something like overrided operator?

Edit: I was trying to simplify code, but this without a and b sometimes output 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!");
      }
   }
}

Upvotes: 1

Views: 91

Answers (1)

nem035
nem035

Reputation: 35481

Doing this

a = null

doesn't set anything else to null but a.

b is left unchanged.

You can think of variables in JS as named pointers to values stored somewhere in memory.

For example, the following code:

var obj = { name: 'bob' };
var a = obj;
var b = obj;

produces two variables, a and b, that both point to obj in memory.

a and b pointing to an object

Now when you do

a = null

You're just making a point to null while b is still pointing to obj.

a pointing to null and b pointing to object

Upvotes: 3

Related Questions