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
};
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 the studentInformation name, 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.
object2 to property names with a space in between (i.e prop 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 2 using 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 of 42.
