I want to do the following in javascript but there’s something about the syntax I’m not understanding here:
var theObj = { foo: val1, bar: val2 }
if ( condition ) {
theObj[foo] = newVal
return theObj // returns { foo: val1, bar: newVal }
}
return theObj // returns { foo: val1, bar: val2 }
What you have is not an object array, but rather an object literal. Normally, its properties would be accessed as
theObj.property, but JavaScript provides an alternative syntax oftheObj["property"]when you need to do operations like string manipulation on the property name (liketheObj["property_" + numberVar]), or for properties not valid in dot notation (like number propertiestheObj[12] = "twelve")If you access the property via
[], you would need to quote the string["foo"], otherwise the parser would be looking for a variable namedfooto insert there. However, this simple string property is better accessed with dot notation: