0

let's see an example:

let object = {
    a: {
        b: 1
    }
};

Now I want to modify the object.a from x:

s.1)

let x = object.a;
x = 2;

console.log(object);

result:

[object Object] {
  a: [object Object] {
    b: 1
  }
}

s.2

let x = object.a;
x = { b: 2 };

console.log(object);

result:

[object Object] {
  a: [object Object] {
    b: 1
  }
}

s.3

let x = object.a;
x.b = 2;
x.c = 2;

console.log(object);

result:

[object Object] {
  a: [object Object] {
    b: 2,
    c: 2
  }
}

Why s.1 and s.2 fail?

azlar
  • 460
  • 1
  • 5
  • 12

1 Answers1

0

In S1 and S2 you are changing the value of X for new values/objects. The reference to "object" is broken and assigned a new pointer. Hence, you are no longer changing the "original" object.

However, on S3, you are modifying properties of the existing object. The reference is still maintained and, hence, you're changing both "object" and "x" properties at once.

nitobuendia
  • 1,228
  • 7
  • 18