JavaScript Objects Help

JavaScript Objects Help
0

#1

Hello everyone, am just not getting a simple task. Why is that the properties in the Example 1 has double quotes while in the Example 2, it doesn’t?!

Would really appreciate an explanation on this. Thank you :slight_smile:

Example 1:

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

Example 2:

var myObj = {
gift: “pony”,
pet: “kitten”,
bed: “sleigh”
};


#2

When you write it in the format of the 2nd example, JavaScript understands the property names are strings, so it is not required to put the quotes around them. The exception to this rule would be if you had a property name with a space in it such as the following, then you would have to put quotes around it.

var obj = {
  myprop: 100,  // does not need quotes
  "your prop": 200 // needs quotes because of the space
};
console.log(obj.myprop); // displays 100
console.log(obj["your prop"]); // displays 200 and note the use of bracket notation here because of the space in the property name

#3

Got it. Wow that was logical. Thank you so much.