Is that why Doberman came to the console?

Viewed 45

var dogs = {
    Fido: "Mutt",
    Hunter: "Doberman",
    Snoopie: "Beagle"
};
var myDog = "Hunter";
var myBreed = dogs[myDog];
console.log(myBreed); // "Doberman"

2 Answers

What's your question? Why Doberman is output?

Well, JS you can read object properties as arrays or maps, where you indicate the "key".
For every property into the object, the name is the key, so your object dogs has keys: Fido, Hunter and Snoopie.

Now, you have another value stored into myDog variable. When you do dogs[myDog] is equal as dogs["Hunter"].

And as I've explained before, you can use the key to acces the value object.

In this case, the value for Hunter is Doberman.

This is why ouput by console.

There is a key value relationships in objects in JavaScript. this means that you can access the value (in this example "Doberman") by using the key (in this example "Hunter").

There are mainly 2 ways to access the values of the object. Either by using

object.key

or

object[key]

On the above example you used the second.

Related