Search code examples
javascriptdestructuringprimitive-types

Why changing a Number value in destructured object, change also the value in the original object?


I have declared the following object:

const restaurant = {
  openingHours: {
    thu: {
      open: 12,
      close: 22,
    },
    fri: {
      open: 11,
      close: 23,
    },
    saturday: {
      open: 0, // Open 24 hours
      close: 24,
    },
  }
};

than i desturctured openingHours object into a new variable name friday:

const { fri: friday } = restaurant.openingHours;

than i modified the value of open hour property in friday object:

friday.open = 5;

and in the end i checked if the change affect original restaurant property:

console.log(restaurant.openingHours.fri.open, friday.open); // prints 5 5

I can't understand why it change the value of restaurant.openingHours.fri.open to 5?

Cause if i had the following code:

let originalAge =5;
let newAge = originalAge;
newAge =6;
console.log(originalAge) // will print 5, So what is the difference here?

enter image description here


Solution

  • The following destructuing syntax:

    const { fri: friday } = restaurant.openingHours;
    

    ... desugars to:

    const friday = restaurant.openingHours.fri;
    

    Both of the above set the variable friday to a reference to the object:

    {
      open: 11,
      close: 23,
    }
    

    Since the above object is also the same reference in your restaurant.openingHours.fri object, both friday and restaurant.openingHours.fri will be referencing the same object in memory. As a result, when you do:

    friday.open = 5;
    

    you're changing the one object in memory, which both friday and restaurant.openingHours.fri are pointing to.

    In your example, however, you're working with primitives (ie: 5), which are copied by value. And so they are not shared in your memory (so changing one does not change the other).

    One way you can make a copy of the .fri object by updating your destructuring syntax to use the rest syntax:

    const { fri: {...friday} } = restaurant.openingHours;
    

    const restaurant = {
      openingHours: {
        thu: {
          open: 12,
          close: 22,
        },
        fri: {
          open: 11,
          close: 23,
        },
        saturday: {
          open: 0, // Open 24 hours
          close: 24,
        },
      }
    };
    
    const { fri: {...friday} } = restaurant.openingHours;
    friday.open = 5;
    console.log(friday, restaurant.openingHours.fri);