Submodule 12.2: JavaScript Objects
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:
objectName.property
Example:console.log(darkChoco.milk);
objectName["property"]
Example:console.log(darkChoco["milk"]);
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
- Open your editor, create a new file and save it as
exersice12.2.03.html
in the folder "yourNameWEB2JS". - Using the above code modify the file. The browser's output should be as shown in the following image: