here is an object:
"prop name": "prop value one",
propName: "prop value two",
key: "key value"
console.log(obj.propName) //"prop value two"
console.log(obj.["propName"]) //"prop value two"
console.log(obj.[propName]) //"key value"
console.log(obj.["key"]) //"key value"
console.log(obj.[key]) // undefined(variable key is not defined)
console.log(obj.["prop name"]) //"prop value one"
console.log(obj."prop name") //invalid syntax
You are confusing the explanation about rules for property names and rules for referencing them. When you declare a property inside an object, which is more than a word, you need to represent its value as a string, using quotes. For exampe the property “prop name” need to be in quotes.
propName however dont have to be, because its one word. So i declared
key properties without using quotes, but for
prop name i dont have this option.
Regarding reference, to access
propName value, we can say
obj["propName"]. We can use dot notation, when we know beforehand the name of the property, however, when the property name is more than one word, we must use bracket notation:
obj["prop name"]. Bracket notation evaluates the expression inside the brackets and then uses the value as a reference for the property name. If i say
obj["propName"], the value inside the brackets is the string “propName” and the reference leads to that property in the object, but if i write
obj[propName], it will look for the value inside the
propName variable, which in the end would be equal to
obj["key"], as i declared the
propName variable value equal “key”, thus the reference will lead to that object property. Like i said, brackets evaluates whats written within, unlike dot notation, which leads to the explicit value. You could even write
obj["prop"+" "+"name"] to access the
"prop name" property, or use other variables/expression to produce that value.