Basic JavaScript - Accessing Nested Objects

Tell us what’s happening:
I went to Claude to ask what the problem is with this code. and I got back this message. can someone elaborate what the clone and assign messages are meant to say

Let me try explaining this in a different way:

The core issue is that myStorage.car.inside["glove box"] returns a read-only reference to the value “maps”.

When we do:

const gloveBoxContents = "";
gloveBoxContents = myStorage.car.inside["glove box"];

This doesn’t make a copy of “maps” - it just assigns the same read-only reference to the gloveBoxContents variable.

So now gloveBoxContents and myStorage.car.inside["glove box"] point to the same immutable “maps” string.

Later if we tried to do:

gloveBoxContents = "new item"; 

It will throw an error, because we can’t modify that read-only “maps” value.

To fix it, we need to explicitly make a copy of the “maps” string, like:

const gloveBoxContents = JSON.parse(JSON.stringify(myStorage.car.inside["glove box"]));

Now gloveBoxContents points to a new copy of “maps”, not the read-only reference. So we can modify it freely without affecting the original.

The key takeaway is that assigning an object property to a variable doesn’t automatically make a copy - it just creates another reference to the same value. We need to manually copy it to make it writable.

Your code so far

const myStorage = {
  "car": {
    "inside": {
      "glove box": "maps",
      "passenger seat": "crumbs"
     },
    "outside": {
      "trunk": "jack"
    }
  }
};

const gloveBoxContents = " ";


gloveBoxContents = myStorage.car.inside["glove box"];

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5 Safari/605.1.15

Challenge: Basic JavaScript - Accessing Nested Objects

Link to the challenge:

No, it does make a copy of the string “maps”. They are not pointing to the same string.

No, it will throw an error because you defined gloveBoxContents with const, so you can’t can’t change the value of gloveBoxContents after it has been initialized. If you use let instead then it will work.

Did you test this? I just did and it didn’t change the fact that gloveBoxContents was defined with const and thus its value can’t be changed after its initialization.

1 Like