Access Object Properties

Let’s say that we have the object:

var darkChoco = {
cacao:"80%",
milk:"0%",
grams:100
};
var myChoco = "milk";

and we want to access its properties. The 3 different ways by which we can achieve this are:

        1. objectName.property

          Example: console.log(darkChoco.milk);

        2. objectName["property"]

          Example: console.log(darkChoco["milk"]);

        3. objectName[expression]

          Example: console.log(darkChoco[myChoco]);

Note that the 3rd way, it is only possible if the expression inside the [] is equivalent to a property name. In this case, the variable myChoco is equivalent with the property name milk.

Exercise

  1. Open your editor, create a new file and save it as exersice12.2.03.html in the folder "yourNameWEB2JS".
  2. Using the above code modify the file. The browser's output should be as shown in the following image:

Solution: