Codepath

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 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.

  1. Click the Run button. Analyze the different ways to initialize Objects and how values are accessed.
  2. Change the property names in 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 };
  1. Next, access the value of prop 2 using both methods (. symbol or [] symbol).

    console.log(object2."prop 2")
    console.log(object2["prop2"])
  2. Click the Run button and compare your results. Run both console.log() methods separately.

  3. 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.

Fork me on GitHub