Tallaght Campus

Department of Computing

Javascript Objects
  1. Javascript objects

    Javascript objects

    We have already used Javascript objects in this module. For example, we have made many calls to the method getElementById on the object document, which is the Javascript object corresponding to the HTML document. The method call document.getElementById("xyz") returns an object that corresponds to the HTML element with id "xyz". Further, we can read or set properties of this object (e.g. innerHTML or hidden) using the dot notation (e.g. document.getElementById("xyz").innerHTML = "Hello";).

    However, so far we have only worked with objects that were defined and created for us by functions and methods of the Web API. Here we will define and create our own objects from scratch.

    Syntax for object literals

    { name-value-pair-list }
    characters in blue
    Must appear literally as shown.
    name-value-pair-list
    A comma-separated list of 0 or more name-value pairs, e.g. three pairs:

    property-name : value-expression , property-name : value-expression , property-name : value-expression

    where property-name is a valid Javascript identifier and value-expression is a valid expression.

  2. Object examples

    Object examples

    Object literals

    const emptyObject = {};
    const person = { firstname: "John", surname: "Doe"};

    Accessing object properties

    // dot notation
    console.log(person.firstname);
    
    // index notation
    console.log(person["surname"]);	

    Modifying objects

    // set a property to a new value
    person["firstname"] = "Jane";
    person.surname = "Hoe";
    
    // add a new property
    person.age = 97;
    person["address"] = "Yellow cottage at the end of the village";
    
    // delete a property
    delete person.address;

    Checking if an object has a property

    let prop = "firstname";
    if (prop in person) {
        console.log("The object person has a property called " + prop);
    } else {
        console.log("The object person does not have a property called " + prop);
    }			

    Iterating through properties of an object

    for (property in person) {
        console.log("Property " + property + " has value " + person[property]);
    }

    Nesting objects in objects and arrays

    // create another person 
    const person2 = { name: "Johnny",
                      surname: "McGorey", age: 25 };
    
    // create a third person (note that the address property has an object as its value)
    const person3 = { name: "Maximillian",
                      surname: "Mini",
                      age: 1,
                      address: { number: 3, street: "Longroad" }};
    
    // create an array of people
    let myPeople = [ person, person2, person3 ];

    Copying objects

    // creating a new name for an existing object
    let person4 = person;
    
    // changes in person4 will be reflected in person
    person4.firstname = "Jenny";
    
    // check person
    person
    
    // creating a new object from an existing object
    let person5 = {};
    Object.assign(person5, person);
    
    // changes in person5 will not be reflected in person as this is a different object
    person5.firstname = "Joe"
    
    // check person
    person			
  3. Object exercises

    Object exercises

    1. We are given the following structure:
      
      let friendsForTea = [
          { name: "Ali", beverage: "tea" },
          { name: "Ben", beverage: "coffee" },
          { name: "Con", beverage: "tea" },
          { name: "Dan", beverage: "tea" },
          { name: "Eva", beverage: "coffee" },
          { name: "Fae", beverage: "tea"}
      ];
      				    
      How would you describe it in terms of Javascript types?
      • Create a skeleton HTML file and into it add a button ('Print orders') and a section element with an id.
      • Now create a Javascript file, include it in the HTML file and copy the data structure from above into it.
      • Write a function that adds the orders in the format "Ali would like tea", each in a separate paragraph, into the section element.
      • Add the function as handler for clicks on the button and test.
    2. Continuing with the files used in the previous exercise...
      • Add another button ('Print modified orders') and another section with a different id.
      • Now write a second function and add it as handler for clicks on this new button. This function should modify the orders according to the following story and print them into the new section.

        George arrives. He wants hot chocolate. Con and Eva change their minds now that they realise hot chocolate is available and ask for it as well. Ali leaves. Fay notices that her name was misspelt and asks for it to be changed from 'Fae' to 'Fay'.

    Download completed exercises