I’m new to JavaScript following the courses from codecademy.com. Recently they introduced bracket notation (as opposed to the simpler dot notation). I understand there are advantages because you can reference things that you can’t reference using dot notation. However I don’t understand why I’m supposed to use quotes in certain circumstances.
For example:
var suitcase = {
shorts: "purple"
};
if (suitcase.hasOwnProperty("shorts")) {
console.log(suitcase.shorts);
}
Why does shorts need quotes around it in the line if (suitcase.hasOwnProperty("shorts")) {? I’m used to quotes designating something as a string. shorts is a property of the suitcase object so I would think it would be referenced without quotes. So far I’ve been doing well understanding the rules of JavaScript but this wasn’t clearly explained so I find myself confused.
All objects’ properties’ names are just strings. You can always refer to a property by a string name like
a["b"]. The one exception is when you use a.. In that case,a.bis a property. This is equivalent toa["b"]. In all other cases, use strings to refer to property names.hasOwnPropertyis a normal method. If you had passed inshortsrather than"shorts", JS would have treatedshortsas a variable.