JavaScript/Objects/Exercises

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Topic: Objects

1. Be creative.

  • Create an object which describes some of your physical or mental attributes.
  • Show the object with the alert command.
  • Show only the most important attribute of this object with the alert command.
  • Add another property to the object. Show the complete object again.
  • Delete the least important attribute. Show the complete object again.
Click to see solution
"use strict";

// an example

// literal notation
const me = {height:"165 cm", weight: "63 kg", hairColor: "blond"};
alert(JSON.stringify(me));
alert(JSON.stringify(me.height));

me.friendliness = "medium";
alert(JSON.stringify(me));

delete me.hairColor;
alert(JSON.stringify(me));



2. Articles of a warehouse.

  • Create two objects shoe_1 and shoe_2 which characterize shoes. Use the literal notation.
  • Create two other objects shirt_1 and shirt_2 which characterize shirts. First, create empty objects. Then, add attributes to the objects.
  • Create an object warehouse and add all 4 objects to it.
  • Show the price of the 4.-th product out of the warehouse object.
Click to see solution
"use strict";

// literal notation
const shoe_1 = {category:"shoes", type: "sandals", size: 8, color: "brown"};
const shoe_2 = {category:"shoes", type: "high heels", size: 7, color: "silver", price: "94.50"};

// add properties
const shirt_1 = {};
shirt_1.category = "shirts";
shirt_1.size = "XL";
shirt_1["color"] = "blue";
shirt_1["material"] = "cotton";
alert(JSON.stringify(shirt_1));

// mixture
const shirt_2 = {size: "S", color: "green" };
shirt_2.category = "shirts";
shirt_2.price = 19.99;
alert(JSON.stringify(shirt_2));

const warehouse = {prod_1: {...shoe_1}, prod_2: {...shoe_2}, prod_3: {...shirt_1}, prod_4: {...shirt_2} };
alert(JSON.stringify(warehouse));

// the price of the 4.-th product
alert(JSON.stringify(warehouse.prod_4.price));

This example is not very elegant but shows different techniques. In a production environment, you probably would use loops and arrays.