1

Why does the following code snippet below have such a result? variables of type CONST could not have their value changed right?

const theDog = {
  name: 'Totó',
  guardian: { name: 'Alan Turing' }
}
const otherDog = { ...theDog, name: 'Tulipa' }
otherDog.guardian.name = 'Maria Luiza'

theDog? { name: 'Totó', guardian: { name: 'Maria Luiza' } }

  • 2
    The value of the object can't be changed, but its properties still can be. You can use `const otherDog = { ...theDog, guardian: {...theDog.guardian}, name: 'Tulipa' }` to avoid this issue in your example. – Unmitigated Aug 04 '20 at 22:51
  • Related question: [When to use const with objects in JavaScript?](/q/44604212/5764553) – Andrew Myers Aug 04 '20 at 23:07
  • 1
    `otherDog` is a shallow copy of `theDog`. Check out [What is the difference between a deep copy and a shallow copy?](https://stackoverflow.com/q/184710/3982562) and/or have a look at [the Wikipedia page about shallow copying](https://en.wikipedia.org/wiki/Object_copying#Shallow_copy). – 3limin4t0r Aug 04 '20 at 23:15

3 Answers3

0

The problem is that the object is copied with its internal references included, this theDog.guardian and otherDog.guardian refer to the same object.

The solution would be to clone the whole object recursively:

const theDog = {
 name: 'Totó',
 guardian: { name: 'Alan Turing' }
}
const otherDog = Object.assign({}, theDog, {
    name: 'Tulipa'
});
otherDog.guardian.name = 'Maria Luiza'

Also const only specifies that the variable cannot be changed, not the referenced objects

Elias Schablowski
  • 2,619
  • 9
  • 19
0

So, at first you are declaring one variable theDog and the second one is just a reference to the first one. When you are editing the second one you are editing the first one.

If you don't want this, you can use

const resultObject = Object.assign({}, theDog);

to clone it.

0

The value of the object can't be changed, but its properties still can be. You can use object spread syntax on the guardian property to avoid this issue.

const theDog = {
 name: 'Totó',
 guardian: { name: 'Alan Turing' }
}
const otherDog = { ...theDog, guardian: {...theDog.guardian}, name: 'Tulipa' }
otherDog.guardian.name = 'Maria Luiza'
console.log(theDog);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80