Confused - Accessing Objects Properties with the Dot Operator

Hello the below code passed the excercise but I’m confused.
I’m not sure why I had to take the quotation marks off the property to access with dot notation

var testObj = {
“hat”: “ballcap”,
“shirt”: “jersey”,
“shoes”: “cleats”
};

// Only change code below this line

var hatValue = testObj.hat; // Change this line
var shirtValue = testObj.shirt; // Change this line

Dot operator properties never take quotes.

Really, the properties in your object definition don’t need quotes either. You only need them if there is a space or something else weird in the name (or if you’re writing JSON). In normal cases, you can use quotes for the property name, but it is unnecessary.

If there is space, then you can’t use the dot operator, you must use bracket notation.

var testObj = {
  name: "Jennie",
  "phone number": "876-5309"
};

var a = testObj.name;
var b = testObj["phone number"];

Usually we use dot notation and only use bracket if it’s a property name with an unusual character or if we’re using a variable to access the property.

1 Like

@ksjazzguitar Thanks Kevin, that is what I thought.
However the actual task by FreeCodeCamp had property with the quotation marks, which confused me!
My question could be why did FCC add quotations to the property for this task?

I don’t know. Maybe whoever wrote it does that by default. I’d have to go back and look through the materials to see if there is a good reason for that. If not, someone should start an issue.

I just passed this exercise an hour ago and the reason they did it like that is to get you familiar with JSON because that is how it is in JSON (remember the link that you can click to read more about JSON), and I’m pretty sure you can do it that way because javascript converts it to regular property. Javascript allows you to do all sorts of weird stuff.

@ksjazzguitar Thanks Kevin

@zoratu11 Hi Christopher, thanks for your info - I cannot recall or track down the link to read more about JSON. Could you forward me the link if available?

You’ll get to JSON when you get to AJAX. JSON is a data format that is very compatible with JS objects, one of the big differences being that you declare all properties with quotes around them. But once you get them into JS you can treat them like JS objects.

This is also how you declare keys in associative arrays in PHP.

Yeah here is the link http://www.json.org. It’s actually in the exercise titled “Manipulating Complex Objects” so sorry about that. I did alot of exercises today so they all kinda blended together.