-1

I have a following code:

var obj = {
    car: "volvo",
    speed: 20
};

var x = obj.speed;
obj.speed = 500;
console.log(x);
console.log(obj.speed);

obj.speed = 1000;
var y = obj.speed;
console.log(y);

One would expect that x would be 500 at the time you log it to console, however it is still 20. Console.log(obj.speed) results in 500.

Can you let me know why it is like that?

I understand that if I swap theier places: var x declaration and obj.speed = 500, it will point to 500. Just like with y variable

But why? Does the code not check last value of x variable before logging it?

lovemyjob
  • 579
  • 1
  • 5
  • 22

1 Answers1

1

When you are assigning xto obj.speed, It is just similar to assigning a value to a primitive variable.

If you assign value of obj to variable y, then it will get updated as it will be referring to the same memory location.

var obj = {
    car: "volvo",
    speed: 20
};

// Object is a referece data type.
// But you are assigining value of obj.speed which is primitive to the the x
// Hence value of x won't change even if you change the value of obj.speed.

var x = obj.speed;
obj.speed = 500;
console.log(x);


// But if you assign the value of object to another variable `y`
// Now, y will be pointing to the same memory location as that of obj
// If you update the obj, then the value of y will also get updated
var y = obj;
obj.speed = 1000;
console.log(y);
console.log(obj);
Anurag Singh Bisht
  • 2,683
  • 4
  • 20
  • 26