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' } }

3

3 Answers 3

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);

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments