Accessing Objects Properties with Variables lesson

Accessing Objects Properties with Variables lesson
0

#1

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” ?


#2

Answer to 1st question: You created a variable called someProp and assigned it the value “propName”, so when you write:

 myObj[someProp];

that is the same as

myObj["propName"]

Answer to 2nd question: That is just JavaScript syntax when working with objects. When you write:

propName : "Some Value"

inside the object, it is behind the scenes the same as:

"propName" : "Some Value"

#3

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