Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Object-Oriented JavaScript (2015) Introduction to Methods Object Literal Review

Sarath TS
Sarath TS
1,022 Points

Accessing a property inside an object by square bracket.

In the quiz, a property is being accessed via square bracket like below.

var key ="name"; cat[key];

Question is to choose NOT a valid way to access property in an object. And I selected this answer. But system says my answer is wrong. To my understanding while mentioning property via square bracket it should in double quotes. Or is this way of accessing., cat[key] - without double quotes is also valid?

2 Answers

Tomasz Halaczkiewicz
Tomasz Halaczkiewicz
21,845 Points

that "key" passed in a square bracket is a string. It is a string "name" hidden in a variable named "key".

var key ="name"; - here you declare variable key and assign string "name" to it.

cat[key]; - and here you call that variable and the string it holds is being passed.

Hope that helps :)

Sarath TS
Sarath TS
1,022 Points

Yeaaahhhh..., Got it. (y) . Thanks Halaczkiewicz