Object Properties : How does it work?

Here’s the very basic sample code from the task in JS curriculum:

const dogs = {
Fido: “Mutt”,
Hunter: “Doberman”,
Snoopie: “Beagle”

const myDog = “Hunter”;
const myBreed = dogs[myDog];

The question I have, lol, is: WHY does it return anything at all, when calling “myDog” as part of “dogs”? Namely, I don’t get why “myDog” would be accessible as part of the “dogs” object, since it was never added to it.

The way I read it: a string “Hunter” was assigned to “myDog” as its value. But why would one be able to access “myDog” as part of “dogs”?

Could anyone please explain or direct me to a resource that would?

Thanks in advance! :wink:

when we refer to object property using brackets, we put a string inside, the name of the property we wanna call. If i wanted to check the value inside dogs, on the key/property Hunter, and im to use brackets, it would look like dogs['Hunter']. The cool thing is, i can also use a variable instead, which value is the same string. myDog value is equal “Hunter”, so when i put the variable in the brackets, its the value im refering to. In the end, dogs['Hunter'] is equal dogs[myDog]. If i was to look for “myDog” property in that object, id either say dogs.myDog or dogs['myDog'] which would apparently return undefined, as the object has no such property. dogs.Hunter on the other hand, would also return “Doberman”.

1 Like

By using square brackets, the myDog is evaluated before we look up that property. In this case, myDog evaluates to "Hunter", so that reads as dogs["Hunter"].

Had you tried dogs.myDog it would have had an issue, as there is no property by that name. I’d take a look on Property accessors - JavaScript | MDN


Thanks a ton - this very simple aspect explains everything! :smiley:

1 Like

Thanks! In the light of the second answer I see you’re basically saying the same thing :wink:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.