Confused on Accessing Object Properties with Variables


I am on Accessing Object Properties with Variables module and I am confused. Why does the console print “Hunter”? This is the way I read it from what I read:

The variable dogs is created, and inside that variable, there is
Fido: which will produce the string “Mutt”
Hunter: which will produce the string “Doberman”
Snoopie: which will produce the string “Beagle”

Then, the string “Hunter” is assigned a variable myDog

Then, the variable dogs and the variable myDog is assigned a new variable, myBreed.

So, if we print myBreed, it should print

Fido: "Mutt",
  Hunter: "Doberman",
  Snoopie: "Beagle"

and Hunter.

Next time when you ask about a specific lesson, please provide a link so we can click through and see the details.

I don’t see where it says this. The lesson explicitly says differently, actually.

The string Doberman would be displayed in the console.

My apologies, I meant to say "why does the console print “Doberman”?

This lesson, and the previous three on objects are extremely important so I would suggest you review them until you understand every single detail of the examples and the code.

Remember that objects are a group of key-value pairs. In this case, dogs is an object with 3 key-value pairs. “Fido” is the key to the value “Mutt”, “Hunter” is the key to the value “Doberman”, and “Snoopie” is the key to the value “Beagle”.

To access the values inside the object, you need to provide the key. That can be done in two ways, dot notation (two lessons back) or bracket notation (this and the previous lesson).

When you know the literal value of the key ahead of time you can use dot notation.

dogs.Fido // "Mutt"
dogs.Hunter // "Doberman"
dogs.Snoopie // "Beagle"

With bracket notation, the expression inside the brackets is evaluated to a string, and then that string is used as the key.

dogs["Fido"] // "Mutt"
dogs["Hunter"] // "Doberman"
dogs["Snoopie"] // "Beagle"

Notice that when you pass the literal string inside the brackets, it works exactly the same as dot notation.

The powerful thing with bracket notation is that the expression is evaluated, so we can do things like use variables or calculations to create the key string.

dogs["F" + "i" + "d" + "o"] // "Mutt"

const name = "Fido"
dogs[name] // "Mutt"

const otherName = "Hunt" + "er"
dogs[otherName] // "Doberman"

Let me know if anything makes no sense there.

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