Objects
Initializing JavaScript Objects
An Object in JavaScript can be initialized using several notations:
An object initializer is a comma-delimited list of property names and associated values enclosed in curly brackets {}. We already witnessed the use of an object initializer with studentInformation in our starter code.
const objectInit = {
"property1" : value1,
"property2" : value2,
"property3" : value3
};
- Property Names: property names may be single or multiple word strings. Typically, it is best to keep property names a single string. However in some cases, you may have property names multiple words with the use of spaces if they are visible to users on the frontend view.
- Values: The values in an object do not have to be the same data type. The value for the first property may be a string type, while another property value may be a number or object type.
Accessing Property Values in JavaScript Objects
There are two ways of accessing property values of a JavaScript Object
object.propertyName: Using the.symbol accesses the property value. This is what we used in the previous step to get thestudentInformationname, advisor, grade, etc.object[propertyName]: In this notation, we use the square brackets[]to access the property value, this is similar to Array/List notation.
Both methods are acceptable and receive the same value. The first method with use of the . symbol is more widely used by developers as it mimics class Object notations. However, the second is used when property names contain multiple words separated by a space.
Take a look at the example below from MDN docs on the use of object initializers.
-
Click the Run button. Analyze the different ways to initialize Objects and how values are accessed.
-
Change the property names in
object2to property names with a space in between (i.eprop 1,prop 2,prop 3.const a = 'foo'; const b = 42; const c = {}; const object2 = { "prop 1": a, "prop 2": b, "prop 3": c }; -
Next, access the value of
prop 2using both methods (.symbol or[]symbol).console.log(object2."prop 2") console.log(object2["prop2"]) -
Click the Run button and compare your results. Run both
console.log()methods separately. -
You should notice that when using the
.symbol you receive an Error message and when using the[]symbol you get the expected output of42.