To Lecture Notes

IT 238 -- Feb 3, 2025

Review Exercises

  1. How do you write the string "This is a test." to each of these output locations?
    (a) Chrome Console    (b) HTML Document
    (c) Output Dialog        (d) HTML Textfield
    Answer:
    // (a) Write to the Chrome Console:
    console.log("This is a test.");
    // (b) Write to the browser document:
    document.writeln("This is a test.");
    // (c)Display string in output dialog:
    alert("This is a test.");
    
    // (d) Display in an HTML textfield, say with id output.
    function init( ) {
        var textField = document.getElementById("output");
        textField.value = "This is a text.";
    }
    window.addEventListener("load", init);
    
  2. What are the JavaScript operators && and || ?
    Answer: && means logical and; || means logical or.
  3. What is the difference between an array of object literals and JSON?
    Answer: The object literals in an array can be accessed and manipulated. JSON is just a string that must be converted to an object literal or an array of object literals before its data can be accessed.
  4. Which method changes an array of object literals into a JSON string?
    Answer: var jsonString = JSON.stringify(objects);
  5. Which method changes a JSON string into an array of object literals?
    Answer: var objects = JSON.parse(jsonString);
  6. Create an array of book literal objects named books with these properties:

    title author year
    "Tale of Two Cities" "Dickens" 1859
    "Return of the Native" "Hardy" 1878
    "Alice in Wonderland" "Carroll" 1865

    Answer: The zipfile of all source code files for Exercises 5, 6, and 7:
    ex456.zip
    // Script for Exercise 5
    var books =
        [ { title: "Tale of Two Cities",
            author: "Dickens",
            year: 1859 },
          { title: "Return of the Native",
            author: "Hardy",
            year: 1878 },
          { title: "Alice in Wonderland",
            author: "Carroll",
            year: 1865 } ];
    
    // Print array with traditional for loop.
    for(var i = 0; i < books.length; i++) {
        document.writeln(`${books[i].title} `);
        document.writeln(`${books[i].author} `);
        document.writeln(`${books[i].year}<br>`);
    }
    
    // Print array with modern for loop.
    for(var book of books) {
        document.writeln(`${book.title } `);
        document.writeln(`${book.author} `);
        document.writeln(`${book.year}<br>`);
    }
    
  7. Create an object literal student with this information:

    name "Becky"
    quizScores [93, 89, 95, 100]

    Add a toString method that converts the object to a string.
    Answer:
    // Script for Exercise 6
    var student = {
        name: "Becky",
        quizScores: [93, 89, 95, 100],
        toString: function( ) {
            var output = this.name + ";" +
                this.quizScores.toString( );
            return output;
        }
    };
    // toString method is called automatically
    // when the student object is printed.
    document.writeln(student);
    
  8. Create a clock object representing a 24 hour clock with instance variables hr, min, sec, and instance methods toString and tick. Answer:
    // Script for Exercise 7
     clock = { hr: 19, min: 3, sec: 9,
        tick: function( ) {
            this.sec++;
            if(this.sec == 60) {
                this.sec = 0;
                this.min++;
            }
            if(this.min == 60) {
                this.min = 0;
                this.hr++;
            }
            if(this.hr == 24) {
                this.hr = 0;
            }
        },
        toString: function( ) {
            var h = this.hr.toString( ).padStart(2, "0");
            var m = this.min.toString( ).padStart(2, "0");
            var s = this.sec.toString( ).padStart(2, "0");
            return `${h}:${m}:${s}`;
        }
    }
    
    // Test clock object
    document.writeln(clock);
    for(var i = 1; i <= 20000; i++) {
        clock.tick( );
    }
    document.writeln(clock);
    
  9. Using the kids.js file, write scripts that:
    1. output the name and age of all kids that are 9 years old;
      Answer:
      ===== HTML file: index.html ====================
      <!DOCTYPE html>
      <!-- Use this HTML file for exercises
           9b, 9c, and 9d also. -->
      <html lang="en">
          <head>
          <meta charset="UTF-8">
          <title>Kids Examples</title>
          <script src="kids.js"></script>
          <script src="script.js"></script>
      </head>
      <body></body>
      </html>
      ----- JavaScript script: script.js -------------
      // Script for Exercise 9a
      var kidObjects = JSON.parse(kids);
      for(kid of kidObjects) {
          if(kid.age == 9) {
              document.writeln(`${kid.name} ${kid.gender}<br>`);
          }
      }
      ================================================
      
    2. output the name of all the girls that are 11 years old;
      // Script for Exercise 9b
      // Source code file: script.js
      var kidObjects = JSON.parse(kids);
      for(kid of kidObjects) {
          if(kid.age == 11 && kid.gender == "F") {
              document.writeln(`${kid.gender}<br>`);
          }
      }
      
    3. output the gender and age of Joan;
      // Script for Exercise 9c
      // Source code file: script.js
      var kidObjects = JSON.parse(kids);
      for(kid of kidObjects) {
          if(kid.name == "Joan") {
              document.writeln(`${kid.gender} ${kid.age}<br>`);
          }
      }
    4. output the gender and age of the person with name entered in a prompt box;
      Answer:
      // Script for Exercise 9d
      // Source code file: script.js
      var kidObjects = JSON.parse(kids);
      var searchName = prompt("Enter name: ");
      for(kid of kidObjects) {
          if(kid.name == searchName) {
              document.writeln(`${kid.gender} ${kid.age}<br>`);
          }
      }
      
    5. output the gender and age of the person with name entered in a textfield when a button is clicked.
      Answer:
      ======== HTML file: index.html ===============================
      <!DOCTYPE html>
      <html lang="en">
          <head>
              <meta charset="UTF-8">
              <title>Exercise 8e</title>
              <script src="kids.js"></script>
              <script src="script.js"></script>
          </head>
          <body>
              <h1>Exercise 8e</h1>
      
              <label for="txtName">Name:</label><br>
              <input type="text" id="txt-name"><br><br>
      
              <button id="btn1">Display</button><br><br>
      
              <p id="display" />
          </body>
      </html>
      -------- Script file: script.js ==============================
      function displayInfo( ) {
          var input1 = document.getElementById("txt-name");
          var display1 = document.getElementById("display");
          var searchName = input1.value;
          var kidsArray = JSON.parse(kids);
          for(kid of kidsArray) {
              if (kid.name == searchName) {
                  display1.innerHTML = 
                      `${kid.gender} ${kid.age}`;
              }
          }
      }
      
      function init( ) {
          var button1 = document.getElementById("btn1")
          button1.addEventListener("click", displayInfo)
      }
      
      window.addEventListener("load", init);
      -------------------------------------------------------------- 
      
  10. Look at the KidsTextArea1 and KidsTextArea2 Examples.
  11. Using the cities JSON file for Project 2a:
    https://facweb.cdm.depaul.edu/sjost/cities.js,
    output the number of cities represented in the database. It is not necessary to include the JSON file in your project for this exercise.  Access it via its URL instead.
    Here is the script:
    <!DOCTYPE html>
    <!-- Source code for Exercise 11.
         File name: index.html -->
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Cities Example</title>
            <script 
    src="https://facweb.cdm.depaul.edu/sjost/cities.js">
            </script>
            <script src="script.js></script>
       </head>
       <body />
    </html>
    -------------------------------------------
    // Source code for Exercise 11.
    // File name: script.js
    var cities = JSON.parse(data);
    document.writeln(cities.length);
    // or, longer, replace previous line with
    var count = 0;
    for(city of cities) {
        count++;
    }
    document.writeln(count);
    

Functions as First Class Objects

Anonymous Functions

Arrow Notation for Functions