Search⌘ K
AI Features

Solution Review: Shallow Copy

Explore how shallow copies of JavaScript objects share references and can cause unexpected value changes. Understand the risks and behavior of using spread operators and assignments, which is crucial for solving interview questions and writing safer code.

Question 1: Solution review #

In the previous lesson, you were given the following code:

Node.js
const girl = {
name: 'Anna',
info: { age: 20, number: 123 }
};
const newGirl = { ...girl };
newGirl.info.age = 30;
console.log(girl.info.age, newGirl.info.age);

For the code above, you had to answer the following question:

Explanation #

Run the code below to see the output:

Node.js
const girl = {
name: 'Anna',
info: { age: 20, number: 123 }
};
const newGirl = { ...girl };
newGirl.info.age = 30;
console.log(girl.info.age, newGirl.info.age);

As you can see, Option C is the correct answer. Let’s discuss why.

There is an object, girl, that has properties name and info. On line 6, we copy the properties of the girl object into the newGirl object using ...