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 JavaScript Loops, Arrays and Objects Tracking Data Using Objects Mixing and Matching Arrays and Objects

Sandra Vu
Sandra Vu
3,525 Points

" in square bracket notation?

I read the references on StackOverflow and W3 :

obj.["key"]

Code challenge only accepts obj.[key]?

When to use "?

1 Answer

Hi there, you would want to use quotes to hardcode the name of the key. So in your example obj["key"] makes sense if the object is defined with a key named "key". Here are two equivalent ways to access that property:

const obj = {"key": "someValue"};
console.log(obj.key); //someValue
console.log(obj["key"]); //someValue

Bracket notation will evaluate what's in the bracket. Now key can be a variable:

const obj = {"name": "someValue"};
const key = "name";
console.log(obj[key]); // someValue
console.log(obj["key"]); //undefined -- because no property is named "key"

I don't recommend the following, but literals in brackets can allow you to access keys with spaces in them:

const obj = {"what she said": "ermahgerd"};
console.log(obj["what she said"]; //ermahgerd
console.log(obj.what she said); //error -- obj.what is undefined

Also see Mozilla docs on property accessors