Recomended way to access properties in a Javascript Object

Hi there! I wonder if there is a recommended way to “look up” properties on my javascript object, which would help me for every time I need to do this. I got this question doing the Record Challenge Exercise, which the solution is:

imagen

Solution here says I should access properties through bracket notation (example: varName[prop][value]). I’m still confused, I don’t know if always I should access object properties this way or not (should I use dot notation, bracket, both?)

dot notation can be used only on a limited number of situations, if you can use it you need to type less

you can always use bracket notation instead

1 Like

Dot notation is easier to read so preferable where you can use it, but you can’t use it here because you don’t know the keys in advance. It’s used when you already know the actual names of the keys.

collection = {
  1: {
    "artist": "Prince"
  }
}

collection.id.prop is going to error, because there isn’t a key called “id” or one called “prop”. You have a variable called “id”, and one called “prop”, and you need to get the values of those before you look them up, so you have to use the bracket notation – collection[id][prop]. If id is 1 and prop is "artist", then that gets evaluated to collection[1]["artist"], and it works

1 Like