0

Essentially, I have a heavily nested object, so I create variables to access that object so i don't have to write the entire nested object in order to perform an operation.

The problem is that when I create a variable and manipulate it by setting it to null, the variable gets set to null, but the object it's referencing does not.

Conceptually I kind of understand what's going on, but if that's what's going on then I have been wrong about a basic property of javascript for roughly 4 years... which is fine, being wrong is how growth happens, but still.

var thing = { 
    content: { 
        area: { 
            row: { 
              column: {a: 'a', b:'b', c:'c'} 
            } 
        } 
    } 
} 

var contentArea = thing.content.area;
var row = contentArea.row
var column = row.column;

column = null;
console.log(row.column);
// logs  {a: "a", b: "b", c: "c"}
console.log(column);
// logs null
row.column = null;
console.log(row.column);
// logs null.

Can anyone tell me why this happens and point me to a reference where I can read more about why it happens?



it's worth noting that if you try to set something rather than nullifying something, THAT change is persisted. kind of. rather than setting the above to null, try this:

column.a = 'purple';
console.log(row.column);
console.log(column);
//both log {a: "purple", b: "b", c: "c"}

however if you try to set the object to something else, it does not persist to the object:

column = 'purple'
console.log(row.column);
console.log(column);
// logs {a: "a", b: "b", c: "c"}
// 'purple
Andrew Luhring
  • 1,762
  • 1
  • 16
  • 37

1 Answers1

1

Have a look here: Evaluation Strategy - Call by Sharing And this SO question

What is essentially boils down to is this:

  1. Setting a variable in Javascript points it to a new 'value' (primitive object). Thats why nullifying or setting column to 'purple' doesnt change the underlying object. It just points column to something else.

  2. BUT, setting column.a does work, because column is pointing to the same object as your nested column, so setting a property on one will reflect on the other.

Community
  • 1
  • 1
0xRm
  • 1,259
  • 8
  • 11