Having trouble accessing nested properties

Hi, I’m testing out a feature on something I’m building but am having trouble accessing the nested properties of a dummy object. What am I doing wrong?

I think you’ll need to use bracket notation. Like cards[card].front, because card in each loop will point to a key in the cards object as a String.

1 Like

Yeah, looks like that works. thanks! I’m still sort of confused why I can’t just use dot notation through the whole statement—I thought dot and bracket were equivalent syntax?

1 Like

You’re welcome!

The difference between the two methods is when you type cards.card, you’re actually trying to access a card property in the cards object – which it doesn’t have, so it returns undefined; while cards[card] means you’re accessing a property in cards that has the name of what the card loop variabel represents ('card1', 'card2', etc).

So cards.card will access the same property in cards no matter what iteration you are in in the for loop, while cards[card] will refer to each of the properties in cards.

Just remember that the bracket and dot notation are the same only when what you put between the brackets (if you use the bracket notation) is the same as the name of the property (if you use the dot notation).

Huh, ok. Thanks, I’ll remember that. It seems weird to me that “card” is correctly assigned in the second console.log but then switches to a literal when it’s referenced between two dots in a statement.

Maybe a better way to think about it is that using dot notation is simply a shorthand for bracket notation with a string. So cards.card is a shorthand for cards["card"].

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