Table of Contents

~~SLIDESHOW~~

Programming in JavaScript

Contact Hour 8: To be discussed on Wednesday 13th February, 2013.

Lecturer: Dr Chris P. Jobling.

Continuing our introduction to JavaScript with a look at control statements, objects, arrays and functions.


These slides and notes are based on Chapter 4 of Robert W. Sebasta, Programming the World-Wide Web, 3rd Edition, Addison Wesley, 2006. with additional examples and explanation from Chris Bates, Web Programming: Building Internet Applications, 3rd Edition, John Wiley, 2006.

Programming in JavaScript

We continue our quick tour of the basics of JavaScript.

Contents of this Lecture

Learning Outcomes — Control Statements

At the end of this lecture you should be able to answer these questions:

  1. What is a control construct?
  2. What are the three possible forms of control expressions in JavaScript?
  3. What is the difference between == and ===?
  4. What is the difference between a while statement and a do-while statement?

About the examples

I have decided to use jsFiddle to host the examples for this session as this provides a nice way to demonstrate the code and for you to play with the code afterwards. If you want to run the examples yourself you can make use of the template HTML and CSS that has been provided in the examples folder.

Use the script-tag in the provided HTML template to load the external JavaScript file for the example you wish to see run.

Control Statements

Control Expressions

Primitive values

Primitive values can be interpreted as booleans (truthy values)

Relational Expressions


Generally, for safety, you want to avoid coercion as it adds an element of uncertainty, use === and !== rather than == and !=.

Compound Expressions

Selection Statements — if-then-else


var a = 2,
    b = 4,
    element = $('#result'),
    message;
 
if (a > b) {
    message = a + " is greater than " + b;
    console.log(message);
    element.append("<p>" + message + "</p>");
}
else {
    message = a + " is not greater than " + b;
    console.log(message);
    element.append("<p>" + message + "</p>");
    a = b;
}
 
message = "Now a === b is " + (a === b);
 
console.log(message);
element.append("<p>" + message + "</p>");

Selection Statements — Switch

    switch (expression) {
      case value_1:
       // value_1 statements
      case value_2:
       // value_2 statements
      . . .
      default:
       // default statements]
    } 

Example

Using a script to set the border properties of a table (See borders2.html).


1. Initial dialogue

Initial dialogue

2. Result

Result of example 1

3. Code

var bordersize, table, element;
 
element = $('#result');
 
bordersize = prompt("Select a table border size \n" +
    "0 (no border) \n" +
    "1 (1 pixel border) \n" +
    "4 (4 pixel border) \n" +
    "8 (8 pixel border) \n");
 
table = "";
 
switch (bordersize) {
    case "0":
        table += "<table>";
        break;
    case "1":
        table += "<table border = '1'>";
        break;
    case "4":
        table += "<table border = '4'>";
        break;
    case "8":
        table += "<table border = '8'>";
        break;
    default:
        console.error("Error - invalid choice: " + bordersize + "\n");
        table += "<table>";
}
 
table += "<caption> 2003 NFL Divisional Winners </caption>";
table += "<tr>" +
    "<th />" +
    "<th> American Conference </th>" +
    "<th> National Conference </th>" +
    "</tr>" +
    "<tr>" +
    "<th> East </th>" +
    "<td> New England Patriots </td>" +
    "<td> Philadelphia Eagles </td>" +
    "</tr>" +
    "<tr>" +
    "<th> North </th>" +
    "<td> Baltimore Ravens </td>" +
    "<td> Green Bay Packers </td>" +
    "</tr>" +
    "<tr>" +
    "<th> West </th>" +
    "<td> Kansas City Chiefs </td>" +
    "<td> St. Louis Rams </td>" +
    "</tr>" +
    "<tr>" +
    "<th> South </th>" +
    "<td> Indianapolis Colts </td>" +
    "<td> Carolina Panthers </td>" +
    "</tr>" +
    "</table>";
 
console.log(table);
 
element.append(table);

Loop Statements

    do
      statement or compound
    while (control_expression)

// date.js 
//   Illustrates the use of the Date object by 
//   displaying the parts of a current date and
//   using two Date objects to time a calculation
 
var element = $('#result');
 
// Get the current date
var today = new Date();
 
 
// Fetch the various parts of the date
var dateString = today.toLocaleString(),
    day = today.getDay(),
    month = today.getMonth(),
    year = today.getFullYear(),
    timeMilliseconds = today.getTime(),
    hour = today.getHours(),
    minute = today.getMinutes(),
    second = today.getSeconds(),
    millisecond = today.getMilliseconds();
 
// Display the parts of the date
element.append("<p>Date: " + dateString + "<br />" +
    "Day: " + day + "<br />" +
    "Month: " + month + "<br />" +
    "Year: " + year + "<br />" +
    "Time in milliseconds: " + timeMilliseconds + "<br />" +
    "Hour: " + hour + "<br />" +
    "Minute: " + minute + "<br />" +
    "Second: " + second + "<br />" +
    "Millisecond: " + millisecond + "</p>");
 
// Time a loop
 
var dum1 = 1.00149265,
    product = 1;
 
var start = new Date();
 
for (var count = 0; count < 10000; count++) {
    product = product + 1.000002 * dum1 / 1.00001;
}
 
var end = new Date();
var diff = end.getTime() - start.getTime();
element.append("<p>The loop took " + diff + " milliseconds</p>");

Learning Outcomes — Objects

At the end of this lecture you should be able to answer these questions:

Lets play with some objects.

Object Creation

    var myObject = new Object(); 

Object Properties

    var myAirplane = new Object();
    myAirplane.make = "Cessna";
    myAirplane.model = "Centurian"; 

Object Modification

    var property1 = myAirplane.make;
    var property2 = myAirplane["model"]; 
    myAirplane.make = "Boeing";
    myAirplane["model"] = "767"; 
    delete myAirplane.model; 

Object Literals

  var myAirplane = {
    make: "Cessna",
    model: "Centurion"
  };

Please take careful note of the puctuation!

Another Loop Statement

for (var property in myAirplane) {
  console.log(property + ": " + myAirplane[property]);
}

Learning Outcomes — Arrays

At the end of this lecture you should be able to answer these questions:

Fiddle with arrays

Arrays

    var myList = new Array(24, "bread", true);
    var myList2 = [24, "bread", true];
    var myList3 = new Array(24); 

Array Length

    myList[122] = "bitsy";  // length is 123 
    myList.length = 150; 

/*   insert_names.html 
     The script in this document has an array of
     names, name_list, whose values are in 
     alphabetic order. New names are input through
     prompt. Each new name is inserted into the 
     name array, after which the new list is 
     displayed.
*/
 
// The original list of names
var name_list = ["Al", "Betty", "Kasper", "Michael", "Roberto", "Zimbo"];
 
// working variables
var new_name, index, last, result, element = $('#result');
 
// Loop to get a new name and insert it
while (new_name = prompt("Please type a new name", "")) {
 
    // Loop to find the place for the new name
    last = name_list.length - 1;
 
    while (last >= 0 && name_list[last] > new_name) {
        name_list[last + 1] = name_list[last];
        last--;
    }
 
    // Insert the new name into its spot in the array
    name_list[last + 1] = new_name;
 
    // Display the new array
    result = "<p><b>The new name list is:</b><br />";
    element.append();
    for (index = 0; index < name_list.length; index++) {
        result += name_list[index] + "<br />";
    }
    result += "</p>";
    element.append(result);
} //** end of the outer while loop

Array methods

Array Methods (Continued)

    listPart = list.slice(2, 5);
    listPart2 = list.slice(2); 

// nested_arrays.html An example to illustrate an
// array of arrays
 
var element = $('#result'), result_text;
 
// Create an array object with three arrays as its 
// elements
 
var nested_array = [
    [2, 4, 6],
    [1, 3, 5],
    [10, 20, 30]
];
 
// Display the elements of nested_list
result_text = "<p>";
for (var row = 0; row <= 2; row++) {
    result_text += "Row " + row + ":  ";
 
    for (var col = 0; col <= 2; col++) {
        result_text += nested_array[row][col] + " ";
    }
    result_text += "<br />";
}
element.append(result_text + "</p>");

Learning Outcomes — Functions

At the end of this lecture you should be able to answer these questions:

Functions

    function function_name([formal_parameters]) {
      -- body -
    } 

Functions are Objects

ref_fun = fun;
// . . .
ref_fun();  /* A call to fun */ 

Defining Functions

Function Parameters


// parameters.html The params function and a test 
// driver for it. This example illustrates
// function parameters
 
var element = $('#result');
 
// Function describe_params
// Parameters: two named parameters and one unnamed
//             parameter, all numbers
// Returns: nothing
 
function describe_params(a, b) {
    var text = "Function <em>describe_params</em> was passed " + arguments.length + " parameter(s) <br />" +
        "Parameter values are: <br />";
 
    for (var arg = 0; arg < arguments.length; arg++) {
        text += arguments[arg] + "<br />";
    }
    text += "In addition named-parameter <em>a</em> was " + a +
            " and <em>b</em> was " + b;
    return text;
}
 
// A text driver for params
 
element.append("<p>" + describe_params("Mozart") + "</p>");
element.append("<p>" + describe_params("Mozart", "Beethoven") + "</p>");
element.append("<p>" + describe_params("Mozart", "Beethoven", "Tchaikowsky") + "</p>");

Passing a Function: Sorting

    function num_order(a, b) {return a - b;} 
    num_list.sort(num_order);

Function: alternative declaration

Function as variable:

    var function_name = function ([formal_parameters]) {
      -- body -
    };

Another Example


Result of example

// medians.js
// A function and a function tester
// Illustrates array operations
 
 
var element = $('#result');
 
/* 
     Function median
     Parameter: An array of numbers
     Return value: The median of the array
*/
 
var median = function (list) {
    list.sort(function (a, b) {
        return a - b;
    });
    var list_len = list.length;
 
    // Use the modulus operator to determine whether
    //  the array's length is odd or even
    // Use Math.floor to truncate numbers
    // Use Math.round to round numbers
 
    if ((list_len % 2) == 1) {
        return list[Math.floor(list_len / 2)];
    } else {
        return Math.round((list[list_len / 2 - 1] + list[list_len / 2]) / 2);
    }
}; // end of function median -- note semicolon
 
var my_list_1 = [8, 3, 9, 1, 4, 7],
    my_list_2 = [10, -2, 0, 5, 3, 1, 7],
    med;
 
med = median(my_list_1);
element.append("<p>Median of [" + my_list_1 + "] is: " + med + "</p>");
 
med = median(my_list_2);
element.append("<p>Median of [" + my_list_2 + "] is: " + med + "</p>");

Constructors

    function Plane(newMake, newModel, newYear){
      this.make = newMake;
      this.model = newModel;
      this.year = newYear;
    }
 
    myPlane = new Plane("Cessna", "Centurian", "1970"); 

Fiddle with constructors.


Note by convention, constructors use upper case names to distinguish them from ordinary functions. Think proper noun.

Method Properties

    display: function() {
      console.log("Make: " +  this.make);
      console.log("Model: " + this.model);
      console.log("Year: " +  this.year);
    }
  myPlane.display();

Summary of This Lecture

Programming in JavaScript

Learning Outcomes — Control Statements

At the end of this lecture you should be able to answer these questions:

  1. What is a control construct?
  2. What are the three possible forms of control expressions in JavaScript?
  3. What is the difference between == and ===?
  4. What is the difference between a while statement and a do-while statement?

Learning Outcomes — Objects

At the end of this lecture you should be able to answer these questions:

Learning Outcomes — Arrays

At the end of this lecture you should be able to answer these questions:

Learning Outcomes — Functions

At the end of this lecture you should be able to answer these questions:

There are a few more review questions available. You might need to refer to a good JavaScript reference to answer them all.

Exercises

Use jsFiddle or some other method to write, test and debug (if necessary) HTML files that include JavaScript scripts for the following problems. When required to write functions, you must include a script to test the function with at least two different data sets.

  1. Output: A table of numbers from 5 to 15 and their squares and cubes, using alert.
  2. Output: The first 20 Fibonacci numbers, which are defined as in the following sequence 1, 1, 2, 3, … where each number in the sequence is the sum of the two previous numbers. Use console.log to produce the output.
  3. Modify the script of Exercise 2 to input a number, n, using prompt, which is the number of the Fibonacci number required as output.
  4. Function: no_zeros; Parameter: An array of numbers; Result: The array must be modified to remove all zero values. Returns: true if the given array included zeros; false otherwise.

More Homework Exercises

More basic javascript exercises, taken from Chapter 4 of Robert W. Sebasta, Programming the World-Wide Web, 3rd Edition, Addison Wesley, 2006., are available.

What's Next?

Text processing with regular expressions

Previous Lecture | home | Next Lecture