Accessing Objects Properties with Variables lesson

hey

I dont understand in this class example how the object can call a variable which was not part of the object. in the example:

var someProp = “propName”;
var myObj = {
propName: “Some Value”
}
myObj[someProp]; // “Some Value”

var someProp is not belong to the object so how can we call the variable thourgh the myObj object?

Another question is, how come the property propName is without “” shouldn’t it be “propName” : “Some Value” ?

You’re right the variable someProp does not belong to myObj - this is why myObj.someProp or myObj["someProp"] is undefined - but myObj[someProp] is evaluated by first filling in the value of someProp so it becomes myObj["propName"] which is defined and has value "Some Value"

Quotes around property names are not required if the name is a valid identifier name e.g. a name without spaces like propName that can be used for a variable. But property names can be any string so it’s okay to say obj = { "prop A": "value of prop A" } - quotes are also not needed if the property name is a number obj = { 123: "value of prop 123" }

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Using_object_initializers and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors for more details on property names and accessors

1 Like